blob: 674d6deece919005995eb8f0f3bd62370e6a2636 [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>
Peter Collingbournec486ab32021-03-11 12:51:25 -080061#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070063#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080064#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070065#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050066#include <openssl/hmac.h>
67#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070068#include <powermanager/PowerManager.h>
69#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
71#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Peter Collingbournec486ab32021-03-11 12:51:25 -080076using android::base::HwTimeoutMultiplier;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077using android::base::StringPrintf;
78
Garfield Tane84e6f92019-08-29 17:28:41 -070079namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Default input dispatching timeout if there is no focused application or paused window
82// from which to determine an appropriate dispatching timeout.
Peter Collingbournec486ab32021-03-11 12:51:25 -080083const std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108static inline nsecs_t now() {
109 return systemTime(SYSTEM_TIME_MONOTONIC);
110}
111
112static inline const char* toString(bool value) {
113 return value ? "true" : "false";
114}
115
116static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700117 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
118 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119}
120
121static bool isValidKeyAction(int32_t action) {
122 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700123 case AKEY_EVENT_ACTION_DOWN:
124 case AKEY_EVENT_ACTION_UP:
125 return true;
126 default:
127 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128 }
129}
130
131static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700132 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 ALOGE("Key event has invalid action code 0x%x", action);
134 return false;
135 }
136 return true;
137}
138
Michael Wright7b159c92015-05-14 14:48:03 +0100139static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700141 case AMOTION_EVENT_ACTION_DOWN:
142 case AMOTION_EVENT_ACTION_UP:
143 case AMOTION_EVENT_ACTION_CANCEL:
144 case AMOTION_EVENT_ACTION_MOVE:
145 case AMOTION_EVENT_ACTION_OUTSIDE:
146 case AMOTION_EVENT_ACTION_HOVER_ENTER:
147 case AMOTION_EVENT_ACTION_HOVER_MOVE:
148 case AMOTION_EVENT_ACTION_HOVER_EXIT:
149 case AMOTION_EVENT_ACTION_SCROLL:
150 return true;
151 case AMOTION_EVENT_ACTION_POINTER_DOWN:
152 case AMOTION_EVENT_ACTION_POINTER_UP: {
153 int32_t index = getMotionEventActionPointerIndex(action);
154 return index >= 0 && index < pointerCount;
155 }
156 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
157 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
158 return actionButton != 0;
159 default:
160 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 }
162}
163
Michael Wright7b159c92015-05-14 14:48:03 +0100164static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 const PointerProperties* pointerProperties) {
166 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 ALOGE("Motion event has invalid action code 0x%x", action);
168 return false;
169 }
170 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000171 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 return false;
174 }
175 BitSet32 pointerIdBits;
176 for (size_t i = 0; i < pointerCount; i++) {
177 int32_t id = pointerProperties[i].id;
178 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700179 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
180 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 if (pointerIdBits.hasBit(id)) {
184 ALOGE("Motion event has duplicate pointer id %d", id);
185 return false;
186 }
187 pointerIdBits.markBit(id);
188 }
189 return true;
190}
191
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800192static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800194 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 return;
196 }
197
198 bool first = true;
199 Region::const_iterator cur = region.begin();
200 Region::const_iterator const tail = region.end();
201 while (cur != tail) {
202 if (first) {
203 first = false;
204 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 cur++;
209 }
210}
211
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700212/**
213 * Find the entry in std::unordered_map by key, and return it.
214 * If the entry is not found, return a default constructed entry.
215 *
216 * Useful when the entries are vectors, since an empty vector will be returned
217 * if the entry is not found.
218 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
219 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700220template <typename K, typename V>
221static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700222 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700223 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800224}
225
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700226/**
227 * Find the entry in std::unordered_map by value, and remove it.
228 * If more than one entry has the same value, then all matching
229 * key-value pairs will be removed.
230 *
231 * Return true if at least one value has been removed.
232 */
233template <typename K, typename V>
234static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
235 bool removed = false;
236 for (auto it = map.begin(); it != map.end();) {
237 if (it->second == value) {
238 it = map.erase(it);
239 removed = true;
240 } else {
241 it++;
242 }
243 }
244 return removed;
245}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246
chaviwaf87b3e2019-10-01 16:59:28 -0700247static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
248 if (first == second) {
249 return true;
250 }
251
252 if (first == nullptr || second == nullptr) {
253 return false;
254 }
255
256 return first->getToken() == second->getToken();
257}
258
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800259static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
260 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
261}
262
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000263static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
264 EventEntry* eventEntry,
265 int32_t inputTargetFlags) {
266 if (inputTarget.useDefaultPointerInfo()) {
267 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
268 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
269 inputTargetFlags, pointerInfo.xOffset,
270 pointerInfo.yOffset, inputTarget.globalScaleFactor,
271 pointerInfo.windowXScale, pointerInfo.windowYScale);
272 }
273
274 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
275 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
276
277 PointerCoords pointerCoords[motionEntry.pointerCount];
278
279 // Use the first pointer information to normalize all other pointers. This could be any pointer
280 // as long as all other pointers are normalized to the same value and the final DispatchEntry
281 // uses the offset and scale for the normalized pointer.
282 const PointerInfo& firstPointerInfo =
283 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
284
285 // Iterate through all pointers in the event to normalize against the first.
286 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
287 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
288 uint32_t pointerId = uint32_t(pointerProperties.id);
289 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
290
291 // The scale factor is the ratio of the current pointers scale to the normalized scale.
292 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
293 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
294
295 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
296 // First apply the current pointers offset to set the window at 0,0
297 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
298 // Next scale the coordinates.
299 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
300 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
301 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
302 -firstPointerInfo.yOffset);
303 }
304
305 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800306 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
308 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
309 motionEntry.metaState, motionEntry.buttonState,
310 motionEntry.classification, motionEntry.edgeFlags,
311 motionEntry.xPrecision, motionEntry.yPrecision,
312 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
313 motionEntry.downTime, motionEntry.pointerCount,
314 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
315 0 /* yOffset */);
316
317 if (motionEntry.injectionState) {
318 combinedMotionEntry->injectionState = motionEntry.injectionState;
319 combinedMotionEntry->injectionState->refCount += 1;
320 }
321
322 std::unique_ptr<DispatchEntry> dispatchEntry =
323 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
324 inputTargetFlags, firstPointerInfo.xOffset,
325 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
326 firstPointerInfo.windowXScale,
327 firstPointerInfo.windowYScale);
328 combinedMotionEntry->release();
329 return dispatchEntry;
330}
331
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700332static void addGestureMonitors(const std::vector<Monitor>& monitors,
333 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
334 float yOffset = 0) {
335 if (monitors.empty()) {
336 return;
337 }
338 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
339 for (const Monitor& monitor : monitors) {
340 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
341 }
342}
343
Gang Wang342c9272020-01-13 13:15:04 -0500344static std::array<uint8_t, 128> getRandomKey() {
345 std::array<uint8_t, 128> key;
346 if (RAND_bytes(key.data(), key.size()) != 1) {
347 LOG_ALWAYS_FATAL("Can't generate HMAC key");
348 }
349 return key;
350}
351
352// --- HmacKeyManager ---
353
354HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
355
356std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
357 size_t size;
358 switch (event.type) {
359 case VerifiedInputEvent::Type::KEY: {
360 size = sizeof(VerifiedKeyEvent);
361 break;
362 }
363 case VerifiedInputEvent::Type::MOTION: {
364 size = sizeof(VerifiedMotionEvent);
365 break;
366 }
367 }
Gang Wang342c9272020-01-13 13:15:04 -0500368 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700369 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500370}
371
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700372std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500373 // SHA256 always generates 32-bytes result
374 std::array<uint8_t, 32> hash;
375 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700376 uint8_t* result =
377 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500378 if (result == nullptr) {
379 ALOGE("Could not sign the data using HMAC");
380 return INVALID_HMAC;
381 }
382
383 if (hashLen != hash.size()) {
384 ALOGE("HMAC-SHA256 has unexpected length");
385 return INVALID_HMAC;
386 }
387
388 return hash;
389}
390
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391// --- InputDispatcher ---
392
Garfield Tan00f511d2019-06-12 16:55:40 -0700393InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
394 : mPolicy(policy),
395 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700396 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800397 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700398 mAppSwitchSawKeyDown(false),
399 mAppSwitchDueTime(LONG_LONG_MAX),
400 mNextUnblockedEvent(nullptr),
401 mDispatchEnabled(false),
402 mDispatchFrozen(false),
403 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800404 // mInTouchMode will be initialized by the WindowManager to the default device config.
405 // To avoid leaking stack in case that call never comes, and for tests,
406 // initialize it here anyways.
407 mInTouchMode(true),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700408 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800410 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
414 policy->getDispatcherConfiguration(&mConfig);
415}
416
417InputDispatcher::~InputDispatcher() {
418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420
421 resetKeyRepeatLocked();
422 releasePendingEventLocked();
423 drainInboundQueueLocked();
424 }
425
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700426 while (!mConnectionsByFd.empty()) {
427 sp<Connection> connection = mConnectionsByFd.begin()->second;
428 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 }
430}
431
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return ALREADY_EXISTS;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread = std::make_unique<InputThread>(
437 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
438 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439}
440
441status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700442 if (mThread && mThread->isCallingThread()) {
443 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444 return INVALID_OPERATION;
445 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700446 mThread.reset();
447 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450void InputDispatcher::dispatchOnce() {
451 nsecs_t nextWakeupTime = LONG_LONG_MAX;
452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800453 std::scoped_lock _l(mLock);
454 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 // Run a dispatch loop if there are no pending commands.
457 // The dispatch loop might enqueue commands to run afterwards.
458 if (!haveCommandsLocked()) {
459 dispatchOnceInnerLocked(&nextWakeupTime);
460 }
461
462 // Run all pending commands if there are any.
463 // If any commands were run then force the next poll to wake up immediately.
464 if (runCommandsLockedInterruptible()) {
465 nextWakeupTime = LONG_LONG_MIN;
466 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800467
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700468 // If we are still waiting for ack on some events,
469 // we might have to wake up earlier to check if an app is anr'ing.
470 const nsecs_t nextAnrCheck = processAnrsLocked();
471 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
472
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800473 // We are about to enter an infinitely long sleep, because we have no commands or
474 // pending or queued events
475 if (nextWakeupTime == LONG_LONG_MAX) {
476 mDispatcherEnteredIdle.notify_all();
477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 } // release lock
479
480 // Wait for callback or timeout or wake. (make sure we round up, not down)
481 nsecs_t currentTime = now();
482 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
483 mLooper->pollOnce(timeoutMillis);
484}
485
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700486/**
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500487 * Raise ANR if there is no focused window.
488 * Before the ANR is raised, do a final state check:
489 * 1. The currently focused application must be the same one we are waiting for.
490 * 2. Ensure we still don't have a focused window.
491 */
492void InputDispatcher::processNoFocusedWindowAnrLocked() {
493 // Check if the application that we are waiting for is still focused.
494 sp<InputApplicationHandle> focusedApplication =
495 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
496 if (focusedApplication == nullptr ||
497 focusedApplication->getApplicationToken() !=
498 mAwaitedFocusedApplication->getApplicationToken()) {
499 // Unexpected because we should have reset the ANR timer when focused application changed
500 ALOGE("Waited for a focused window, but focused application has already changed to %s",
501 focusedApplication->getName().c_str());
502 return; // The focused application has changed.
503 }
504
505 const sp<InputWindowHandle>& focusedWindowHandle =
506 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
507 if (focusedWindowHandle != nullptr) {
508 return; // We now have a focused window. No need for ANR.
509 }
510 onAnrLocked(mAwaitedFocusedApplication);
511}
512
513/**
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700514 * Check if any of the connections' wait queues have events that are too old.
515 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
516 * Return the time at which we should wake up next.
517 */
518nsecs_t InputDispatcher::processAnrsLocked() {
519 const nsecs_t currentTime = now();
520 nsecs_t nextAnrCheck = LONG_LONG_MAX;
521 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
522 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
523 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500524 processNoFocusedWindowAnrLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700525 mAwaitedFocusedApplication.clear();
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500526 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700527 return LONG_LONG_MIN;
528 } else {
529 // Keep waiting
530 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
531 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
532 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
533 }
534 }
535
536 // Check if any connection ANRs are due
537 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
538 if (currentTime < nextAnrCheck) { // most likely scenario
539 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
540 }
541
542 // If we reached here, we have an unresponsive connection.
543 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
544 if (connection == nullptr) {
545 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
546 return nextAnrCheck;
547 }
548 connection->responsive = false;
549 // Stop waking up for this unresponsive connection
550 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4e219792020-09-22 21:43:09 -0500551 onAnrLocked(*connection);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700552 return LONG_LONG_MIN;
553}
554
555nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
556 sp<InputWindowHandle> window = getWindowHandleLocked(token);
557 if (window != nullptr) {
558 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
559 }
560 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
561}
562
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
564 nsecs_t currentTime = now();
565
Jeff Browndc5992e2014-04-11 01:27:26 -0700566 // Reset the key repeat timer whenever normal dispatch is suspended while the
567 // device is in a non-interactive state. This is to ensure that we abort a key
568 // repeat if the device is just coming out of sleep.
569 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 resetKeyRepeatLocked();
571 }
572
573 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
574 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100575 if (DEBUG_FOCUS) {
576 ALOGD("Dispatch frozen. Waiting some more.");
577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 return;
579 }
580
581 // Optimize latency of app switches.
582 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
583 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
584 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
585 if (mAppSwitchDueTime < *nextWakeupTime) {
586 *nextWakeupTime = mAppSwitchDueTime;
587 }
588
589 // Ready to start a new event.
590 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700591 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700592 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 if (isAppSwitchDue) {
594 // The inbound queue is empty so the app switch key we were waiting
595 // for will never arrive. Stop waiting for it.
596 resetPendingAppSwitchLocked(false);
597 isAppSwitchDue = false;
598 }
599
600 // Synthesize a key repeat if appropriate.
601 if (mKeyRepeatState.lastKeyEntry) {
602 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
603 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
604 } else {
605 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
606 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
607 }
608 }
609 }
610
611 // Nothing to do if there is no pending event.
612 if (!mPendingEvent) {
613 return;
614 }
615 } else {
616 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700617 mPendingEvent = mInboundQueue.front();
618 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 traceInboundQueueLengthLocked();
620 }
621
622 // Poke user activity for this event.
623 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700624 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
627
628 // Now we have an event to dispatch.
629 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700630 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700632 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700634 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700636 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 }
638
639 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700640 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
642
643 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700644 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 ConfigurationChangedEntry* typedEntry =
646 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
647 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 break;
650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700652 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
654 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700655 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700656 break;
657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100659 case EventEntry::Type::FOCUS: {
660 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
661 dispatchFocusLocked(currentTime, typedEntry);
662 done = true;
663 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
664 break;
665 }
666
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700667 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
669 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700670 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700671 resetPendingAppSwitchLocked(true);
672 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700673 } else if (dropReason == DropReason::NOT_DROPPED) {
674 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700675 }
676 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700677 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700680 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
681 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700682 }
683 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
684 break;
685 }
686
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700687 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700688 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700689 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
690 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700692 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700693 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700694 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700695 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
696 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700697 }
698 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
699 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 }
702
703 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700705 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 }
Michael Wright3a981722015-06-10 15:26:13 +0100707 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708
709 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
712}
713
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700714/**
715 * Return true if the events preceding this incoming motion event should be dropped
716 * Return false otherwise (the default behaviour)
717 */
718bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700719 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700720 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700721
722 // Optimize case where the current application is unresponsive and the user
723 // decides to touch a window in a different application.
724 // If the application takes too long to catch up then we drop all events preceding
725 // the touch into the other window.
726 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700727 int32_t displayId = motionEntry.displayId;
728 int32_t x = static_cast<int32_t>(
729 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
730 int32_t y = static_cast<int32_t>(
731 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700732 sp<InputWindowHandle> touchedWindowHandle =
733 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700734 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700735 touchedWindowHandle->getApplicationToken() !=
736 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700737 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700738 ALOGI("Pruning input queue because user touched a different application while waiting "
739 "for %s",
740 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700741 return true;
742 }
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700743
744 // Alternatively, maybe there's a gesture monitor that could handle this event
745 std::vector<TouchedMonitor> gestureMonitors =
746 findTouchedGestureMonitorsLocked(displayId, {});
747 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
748 sp<Connection> connection =
749 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000750 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700751 // This monitor could take more input. Drop all events preceding this
752 // event, so that gesture monitor could get a chance to receive the stream
753 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
754 "responsive gesture monitor that may handle the event",
755 mAwaitedFocusedApplication->getName().c_str());
756 return true;
757 }
758 }
759 }
760
761 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
762 // yet been processed by some connections, the dispatcher will wait for these motion
763 // events to be processed before dispatching the key event. This is because these motion events
764 // may cause a new window to be launched, which the user might expect to receive focus.
765 // To prevent waiting forever for such events, just send the key to the currently focused window
766 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
767 ALOGD("Received a new pointer down event, stop waiting for events to process and "
768 "just send the pending key event to the focused window.");
769 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700770 }
771 return false;
772}
773
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700775 bool needWake = mInboundQueue.empty();
776 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 traceInboundQueueLengthLocked();
778
779 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700780 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 // Optimize app switch latency.
782 // If the application takes too long to catch up then we drop all events preceding
783 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700788 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700793 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 mAppSwitchSawKeyDown = false;
795 needWake = true;
796 }
797 }
798 }
799 break;
800 }
801
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700802 case EventEntry::Type::MOTION: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700803 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
804 mNextUnblockedEvent = entry;
805 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100809 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700810 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
811 break;
812 }
813 case EventEntry::Type::CONFIGURATION_CHANGED:
814 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700815 // nothing to do
816 break;
817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 }
819
820 return needWake;
821}
822
823void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
824 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700825 mRecentQueue.push_back(entry);
826 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
827 mRecentQueue.front()->release();
828 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
830}
831
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700833 int32_t y, TouchState* touchState,
834 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700836 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
837 LOG_ALWAYS_FATAL(
838 "Must provide a valid touch state if adding portal windows or outside targets");
839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800841 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
842 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 const InputWindowInfo* windowInfo = windowHandle->getInfo();
844 if (windowInfo->displayId == displayId) {
845 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846
847 if (windowInfo->visible) {
848 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 bool isTouchModal = (flags &
850 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
851 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800853 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 if (portalToDisplayId != ADISPLAY_ID_NONE &&
855 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800856 if (addPortalWindows) {
857 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700858 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800859 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700860 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 // Found window.
864 return windowHandle;
865 }
866 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800867
868 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700869 touchState->addOrUpdateWindow(windowHandle,
870 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
871 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700876 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
Garfield Tane84e6f92019-08-29 17:28:41 -0700879std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700880 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000881 std::vector<TouchedMonitor> touchedMonitors;
882
883 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
884 addGestureMonitors(monitors, touchedMonitors);
885 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
886 const InputWindowInfo* windowInfo = portalWindow->getInfo();
887 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
889 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000890 }
891 return touchedMonitors;
892}
893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 const char* reason;
896 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 reason = "inbound event was dropped because the policy consumed it";
902 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 case DropReason::DISABLED:
904 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 ALOGI("Dropped event because input dispatch is disabled.");
906 }
907 reason = "inbound event was dropped because input dispatch is disabled";
908 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700909 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 ALOGI("Dropped event because of pending overdue app switch.");
911 reason = "inbound event was dropped because of pending overdue app switch";
912 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700913 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 ALOGI("Dropped event because the current application is not responding and the user "
915 "has started interacting with a different application.");
916 reason = "inbound event was dropped because the current application is not responding "
917 "and the user has started interacting with a different application";
918 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700919 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 ALOGI("Dropped event because it is stale.");
921 reason = "inbound event was dropped because it is stale";
922 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 case DropReason::NOT_DROPPED: {
924 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700930 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
932 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700935 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700936 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
937 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
939 synthesizeCancelationEventsForAllConnectionsLocked(options);
940 } else {
941 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
942 synthesizeCancelationEventsForAllConnectionsLocked(options);
943 }
944 break;
945 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100946 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700947 case EventEntry::Type::CONFIGURATION_CHANGED:
948 case EventEntry::Type::DEVICE_RESET: {
949 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
950 break;
951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
953}
954
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800955static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
957 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700960bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
961 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
962 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
963 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964}
965
966bool InputDispatcher::isAppSwitchPendingLocked() {
967 return mAppSwitchDueTime != LONG_LONG_MAX;
968}
969
970void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
971 mAppSwitchDueTime = LONG_LONG_MAX;
972
973#if DEBUG_APP_SWITCH
974 if (handled) {
975 ALOGD("App switch has arrived.");
976 } else {
977 ALOGD("App switch was abandoned.");
978 }
979#endif
980}
981
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700983 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984}
985
986bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 return false;
989 }
990
991 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700992 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700993 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700995 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996
997 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700998 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 return true;
1000}
1001
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001002void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1003 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004}
1005
1006void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001007 while (!mInboundQueue.empty()) {
1008 EventEntry* entry = mInboundQueue.front();
1009 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 releaseInboundEventLocked(entry);
1011 }
1012 traceInboundQueueLengthLocked();
1013}
1014
1015void InputDispatcher::releasePendingEventLocked() {
1016 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001018 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 }
1020}
1021
1022void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1023 InjectionState* injectionState = entry->injectionState;
1024 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1025#if DEBUG_DISPATCH_CYCLE
1026 ALOGD("Injected inbound event was dropped.");
1027#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001028 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001031 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
1033 addRecentEventLocked(entry);
1034 entry->release();
1035}
1036
1037void InputDispatcher::resetKeyRepeatLocked() {
1038 if (mKeyRepeatState.lastKeyEntry) {
1039 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042}
1043
Garfield Tane84e6f92019-08-29 17:28:41 -07001044KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1046
1047 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001048 uint32_t policyFlags = entry->policyFlags &
1049 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 if (entry->refCount == 1) {
1051 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -08001052 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 entry->eventTime = currentTime;
1054 entry->policyFlags = policyFlags;
1055 entry->repeatCount += 1;
1056 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001058 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001059 entry->displayId, policyFlags, entry->action, entry->flags,
1060 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062
1063 mKeyRepeatState.lastKeyEntry = newEntry;
1064 entry->release();
1065
1066 entry = newEntry;
1067 }
1068 entry->syntheticRepeat = true;
1069
1070 // Increment reference count since we keep a reference to the event in
1071 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1072 entry->refCount += 1;
1073
1074 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1075 return entry;
1076}
1077
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1079 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001081 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082#endif
1083
1084 // Reset key repeating in case a keyboard device was added or removed or something.
1085 resetKeyRepeatLocked();
1086
1087 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1089 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001091 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 return true;
1093}
1094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001097 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099#endif
1100
liushenxiangfea99012021-05-21 20:24:09 +08001101 // Reset key repeating in case a keyboard device was disabled or enabled.
1102 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1103 resetKeyRepeatLocked();
1104 }
1105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 options.deviceId = entry->deviceId;
1108 synthesizeCancelationEventsForAllConnectionsLocked(options);
1109 return true;
1110}
1111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001113 if (mPendingEvent != nullptr) {
1114 // Move the pending event to the front of the queue. This will give the chance
1115 // for the pending event to get dispatched to the newly focused window
1116 mInboundQueue.push_front(mPendingEvent);
1117 mPendingEvent = nullptr;
1118 }
1119
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001120 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001121 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001122
1123 // This event should go to the front of the queue, but behind all other focus events
1124 // Find the last focus event, and insert right after it
1125 std::deque<EventEntry*>::reverse_iterator it =
1126 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1127 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1128
1129 // Maintain the order of focus events. Insert the entry after all other focus events.
1130 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001131}
1132
1133void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1134 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1135 if (channel == nullptr) {
1136 return; // Window has gone away
1137 }
1138 InputTarget target;
1139 target.inputChannel = channel;
1140 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1141 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001142
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001143 dispatchEventLocked(currentTime, entry, {target});
1144}
1145
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 if (!entry->dispatchInProgress) {
1150 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1151 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1152 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1153 if (mKeyRepeatState.lastKeyEntry &&
1154 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 // We have seen two identical key downs in a row which indicates that the device
1156 // driver is automatically generating key repeats itself. We take note of the
1157 // repeat here, but we disable our own next key repeat timer since it is clear that
1158 // we will not need to synthesize key repeats ourselves.
1159 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1160 resetKeyRepeatLocked();
1161 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1162 } else {
1163 // Not a repeat. Save key down state in case we do see a repeat later.
1164 resetKeyRepeatLocked();
1165 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1166 }
1167 mKeyRepeatState.lastKeyEntry = entry;
1168 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 resetKeyRepeatLocked();
1171 }
1172
1173 if (entry->repeatCount == 1) {
1174 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1175 } else {
1176 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1177 }
1178
1179 entry->dispatchInProgress = true;
1180
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001181 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
1183
1184 // Handle case where the policy asked us to try again later last time.
1185 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1186 if (currentTime < entry->interceptKeyWakeupTime) {
1187 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1188 *nextWakeupTime = entry->interceptKeyWakeupTime;
1189 }
1190 return false; // wait until next wakeup
1191 }
1192 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1193 entry->interceptKeyWakeupTime = 0;
1194 }
1195
1196 // Give the policy a chance to intercept the key.
1197 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1198 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001199 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001200 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001201 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001202 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001203 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001207 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 entry->refCount += 1;
1209 return false; // wait for the command to run
1210 } else {
1211 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1212 }
1213 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001214 if (*dropReason == DropReason::NOT_DROPPED) {
1215 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
1217 }
1218
1219 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001220 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001222 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001224 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 return true;
1226 }
1227
1228 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001229 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001231 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1233 return false;
1234 }
1235
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001236 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1238 return true;
1239 }
1240
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001241 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
1244 // Dispatch the key.
1245 dispatchEventLocked(currentTime, entry, inputTargets);
1246 return true;
1247}
1248
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001249void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001251 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1253 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1255 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1256 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257#endif
1258}
1259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1261 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001262 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 entry->dispatchInProgress = true;
1266
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001267 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 }
1269
1270 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001271 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001273 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001274 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 return true;
1276 }
1277
1278 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1279
1280 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001281 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
1283 bool conflictingPointerActions = false;
1284 int32_t injectionResult;
1285 if (isPointerEvent) {
1286 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001287 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001288 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 } else {
1291 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001293 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
1295 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1296 return false;
1297 }
1298
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001299 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001300 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1301 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1302 return true;
1303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001305 CancelationOptions::Mode mode(isPointerEvent
1306 ? CancelationOptions::CANCEL_POINTER_EVENTS
1307 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1308 CancelationOptions options(mode, "input event injection failed");
1309 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 return true;
1311 }
1312
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001313 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001314 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001316 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001317 std::unordered_map<int32_t, TouchState>::iterator it =
1318 mTouchStatesByDisplay.find(entry->displayId);
1319 if (it != mTouchStatesByDisplay.end()) {
1320 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001321 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001322 // The event has gone through these portal windows, so we add monitoring targets of
1323 // the corresponding displays as well.
1324 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001325 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001326 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001328 }
1329 }
1330 }
1331 }
1332
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 // Dispatch the motion.
1334 if (conflictingPointerActions) {
1335 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 synthesizeCancelationEventsForAllConnectionsLocked(options);
1338 }
1339 dispatchEventLocked(currentTime, entry, inputTargets);
1340 return true;
1341}
1342
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001343void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001345 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001346 ", policyFlags=0x%x, "
1347 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1348 "metaState=0x%x, buttonState=0x%x,"
1349 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001350 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1351 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1352 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001354 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 "x=%f, y=%f, pressure=%f, size=%f, "
1357 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1358 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001359 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1360 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1361 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1362 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1363 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1364 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1365 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1366 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1367 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1368 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 }
1370#endif
1371}
1372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1374 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001375 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376#if DEBUG_DISPATCH_CYCLE
1377 ALOGD("dispatchEventToCurrentInputTargets");
1378#endif
1379
1380 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001382 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001384 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001385 sp<Connection> connection =
1386 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001387 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001388 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001390 if (DEBUG_FOCUS) {
1391 ALOGD("Dropping event delivery to target with channel '%s' because it "
1392 "is no longer registered with the input dispatcher.",
1393 inputTarget.inputChannel->getName().c_str());
1394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
1396 }
1397}
1398
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001399void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1400 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1401 // If the policy decides to close the app, we will get a channel removal event via
1402 // unregisterInputChannel, and will clean up the connection that way. We are already not
1403 // sending new pointers to the connection when it blocked, but focused events will continue to
1404 // pile up.
1405 ALOGW("Canceling events for %s because it is unresponsive",
1406 connection->inputChannel->getName().c_str());
1407 if (connection->status == Connection::STATUS_NORMAL) {
1408 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1409 "application not responding");
1410 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 }
1412}
1413
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001414void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001415 if (DEBUG_FOCUS) {
1416 ALOGD("Resetting ANR timeouts.");
1417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418
1419 // Reset input target wait timeout.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001420 mNoFocusedWindowTimeoutTime = std::nullopt;
1421 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422}
1423
Tiger Huang721e26f2018-07-24 22:26:19 +08001424/**
1425 * Get the display id that the given event should go to. If this event specifies a valid display id,
1426 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1427 * Focused display is the display that the user most recently interacted with.
1428 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001429int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001430 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001432 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1434 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 break;
1436 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001437 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001438 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1439 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 break;
1441 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001442 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001443 case EventEntry::Type::CONFIGURATION_CHANGED:
1444 case EventEntry::Type::DEVICE_RESET: {
1445 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 return ADISPLAY_ID_NONE;
1447 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001448 }
1449 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1450}
1451
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001452bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1453 const char* focusedWindowName) {
1454 if (mAnrTracker.empty()) {
1455 // already processed all events that we waited for
1456 mKeyIsWaitingForEventsTimeout = std::nullopt;
1457 return false;
1458 }
1459
1460 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1461 // Start the timer
1462 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1463 "focus to change",
1464 focusedWindowName);
1465 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1466 return true;
1467 }
1468
1469 // We still have pending events, and already started the timer
1470 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1471 return true; // Still waiting
1472 }
1473
1474 // Waited too long, and some connection still hasn't processed all motions
1475 // Just send the key to the focused window
1476 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1477 focusedWindowName);
1478 mKeyIsWaitingForEventsTimeout = std::nullopt;
1479 return false;
1480}
1481
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001483 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 std::vector<InputTarget>& inputTargets,
1485 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001486 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487
Tiger Huang721e26f2018-07-24 22:26:19 +08001488 int32_t displayId = getTargetDisplayId(entry);
1489 sp<InputWindowHandle> focusedWindowHandle =
1490 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1491 sp<InputApplicationHandle> focusedApplicationHandle =
1492 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // If there is no currently focused window and no focused application
1495 // then drop the event.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001496 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1497 ALOGI("Dropping %s event because there is no focused window or focused application in "
1498 "display %" PRId32 ".",
1499 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001500 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001503 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1504 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1505 // start interacting with another application via touch (app switch). This code can be removed
1506 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1507 // an app is expected to have a focused window.
1508 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1509 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1510 // We just discovered that there's no focused window. Start the ANR timer
1511 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1512 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1513 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1514 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakou265ab012020-09-08 19:43:33 -05001515 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001516 ALOGW("Waiting because no window has focus but %s may eventually add a "
1517 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1518 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1519 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1520 return INPUT_EVENT_INJECTION_PENDING;
1521 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1522 // Already raised ANR. Drop the event
1523 ALOGE("Dropping %s event because there is no focused window",
1524 EventEntry::typeToString(entry.type));
1525 return INPUT_EVENT_INJECTION_FAILED;
1526 } else {
1527 // Still waiting for the focused window
1528 return INPUT_EVENT_INJECTION_PENDING;
1529 }
1530 }
1531
1532 // we have a valid, non-null focused window
1533 resetNoFocusedWindowTimeoutLocked();
1534
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001536 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001537 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 }
1539
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001540 if (focusedWindowHandle->getInfo()->paused) {
1541 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1542 return INPUT_EVENT_INJECTION_PENDING;
1543 }
1544
1545 // If the event is a key event, then we must wait for all previous events to
1546 // complete before delivering it because previous events may have the
1547 // side-effect of transferring focus to a different window and we want to
1548 // ensure that the following keys are sent to the new window.
1549 //
1550 // Suppose the user touches a button in a window then immediately presses "A".
1551 // If the button causes a pop-up window to appear then we want to ensure that
1552 // the "A" key is delivered to the new pop-up window. This is because users
1553 // often anticipate pending UI changes when typing on a keyboard.
1554 // To obtain this behavior, we must serialize key events with respect to all
1555 // prior input events.
1556 if (entry.type == EventEntry::Type::KEY) {
1557 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1558 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1559 return INPUT_EVENT_INJECTION_PENDING;
1560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 }
1562
1563 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001564 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1566 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567
1568 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001569 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570}
1571
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001572/**
1573 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1574 * that are currently unresponsive.
1575 */
1576std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1577 const std::vector<TouchedMonitor>& monitors) const {
1578 std::vector<TouchedMonitor> responsiveMonitors;
1579 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1580 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1581 sp<Connection> connection = getConnectionLocked(
1582 monitor.monitor.inputChannel->getConnectionToken());
1583 if (connection == nullptr) {
1584 ALOGE("Could not find connection for monitor %s",
1585 monitor.monitor.inputChannel->getName().c_str());
1586 return false;
1587 }
1588 if (!connection->responsive) {
1589 ALOGW("Unresponsive monitor %s will not get the new gesture",
1590 connection->inputChannel->getName().c_str());
1591 return false;
1592 }
1593 return true;
1594 });
1595 return responsiveMonitors;
1596}
1597
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001599 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001600 std::vector<InputTarget>& inputTargets,
1601 nsecs_t* nextWakeupTime,
1602 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001603 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 enum InjectionPermission {
1605 INJECTION_PERMISSION_UNKNOWN,
1606 INJECTION_PERMISSION_GRANTED,
1607 INJECTION_PERMISSION_DENIED
1608 };
1609
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 // For security reasons, we defer updating the touch state until we are sure that
1611 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 int32_t displayId = entry.displayId;
1613 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1615
1616 // Update the touch state as needed based on the properties of the touch event.
1617 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1618 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1619 sp<InputWindowHandle> newHoverWindowHandle;
1620
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001621 // Copy current touch state into tempTouchState.
1622 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1623 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001624 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001625 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001626 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1627 mTouchStatesByDisplay.find(displayId);
1628 if (oldStateIt != mTouchStatesByDisplay.end()) {
1629 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001630 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001631 }
1632
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001633 bool isSplit = tempTouchState.split;
1634 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1635 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1636 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001637 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1638 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1639 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1640 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1641 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 bool wrongDevice = false;
1644 if (newGesture) {
1645 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001646 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001647 ALOGI("Dropping event because a pointer for a different device is already down "
1648 "in display %" PRId32,
1649 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001650 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1652 switchedDevice = false;
1653 wrongDevice = true;
1654 goto Failed;
1655 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001656 tempTouchState.reset();
1657 tempTouchState.down = down;
1658 tempTouchState.deviceId = entry.deviceId;
1659 tempTouchState.source = entry.source;
1660 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001662 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001663 ALOGI("Dropping move event because a pointer for a different device is already active "
1664 "in display %" PRId32,
1665 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001666 // TODO: test multiple simultaneous input streams.
1667 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1668 switchedDevice = false;
1669 wrongDevice = true;
1670 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 }
1672
1673 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1674 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1675
Garfield Tan00f511d2019-06-12 16:55:40 -07001676 int32_t x;
1677 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001679 // Always dispatch mouse events to cursor position.
1680 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001681 x = int32_t(entry.xCursorPosition);
1682 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001683 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001684 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1685 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001686 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001689 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1690 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001691
1692 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001693 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001694 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001697 if (newTouchedWindowHandle != nullptr &&
1698 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001699 // New window supports splitting, but we should never split mouse events.
1700 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 } else if (isSplit) {
1702 // New window does not support splitting but we have already split events.
1703 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001704 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 }
1706
1707 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001708 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001710 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001711 }
1712
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001713 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1714 ALOGI("Not sending touch event to %s because it is paused",
1715 newTouchedWindowHandle->getName().c_str());
1716 newTouchedWindowHandle = nullptr;
1717 }
1718
1719 if (newTouchedWindowHandle != nullptr) {
1720 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1721 if (connection == nullptr) {
1722 ALOGI("Could not find connection for %s",
1723 newTouchedWindowHandle->getName().c_str());
1724 newTouchedWindowHandle = nullptr;
1725 } else if (!connection->responsive) {
1726 // don't send the new touch to an unresponsive window
1727 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1728 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1729 newTouchedWindowHandle = nullptr;
1730 }
1731 }
1732
1733 // Also don't send the new touch event to unresponsive gesture monitors
1734 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1735
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1737 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 "(%d, %d) in display %" PRId32 ".",
1739 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1741 goto Failed;
1742 }
1743
1744 if (newTouchedWindowHandle != nullptr) {
1745 // Set target flags.
1746 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1747 if (isSplit) {
1748 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001750 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1751 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1752 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1753 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1754 }
1755
1756 // Update hover state.
1757 if (isHoverAction) {
1758 newHoverWindowHandle = newTouchedWindowHandle;
1759 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1760 newHoverWindowHandle = mLastHoverWindowHandle;
1761 }
1762
1763 // Update the temporary touch state.
1764 BitSet32 pointerIds;
1765 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001766 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001767 pointerIds.markBit(pointerId);
1768 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001769 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 }
1771
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001772 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 } else {
1774 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1775
1776 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001777 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001778 if (DEBUG_FOCUS) {
1779 ALOGD("Dropping event because the pointer is not down or we previously "
1780 "dropped the pointer down event in display %" PRId32,
1781 displayId);
1782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1784 goto Failed;
1785 }
1786
1787 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001788 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001789 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1791 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792
1793 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001794 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001796 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1798 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001799 if (DEBUG_FOCUS) {
1800 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1801 oldTouchedWindowHandle->getName().c_str(),
1802 newTouchedWindowHandle->getName().c_str(), displayId);
1803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001805 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1806 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1807 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
1809 // Make a slippery entrance into the new window.
1810 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1811 isSplit = true;
1812 }
1813
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001814 int32_t targetFlags =
1815 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 if (isSplit) {
1817 targetFlags |= InputTarget::FLAG_SPLIT;
1818 }
1819 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1820 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1821 }
1822
1823 BitSet32 pointerIds;
1824 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001827 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 }
1829 }
1830 }
1831
1832 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1833 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001834 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835#if DEBUG_HOVER
1836 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001839 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1840 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842
1843 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001844 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845#if DEBUG_HOVER
1846 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001849 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1850 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1851 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 }
1853 }
1854
1855 // Check permission to inject into all touched foreground windows and ensure there
1856 // is at least one touched foreground window.
1857 {
1858 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001859 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1861 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001862 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1864 injectionPermission = INJECTION_PERMISSION_DENIED;
1865 goto Failed;
1866 }
1867 }
1868 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001869 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001871 ALOGI("Dropping event because there is no touched foreground window in display "
1872 "%" PRId32 " or gesture monitor to receive it.",
1873 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1875 goto Failed;
1876 }
1877
1878 // Permission granted to injection into all touched foreground windows.
1879 injectionPermission = INJECTION_PERMISSION_GRANTED;
1880 }
1881
1882 // Check whether windows listening for outside touches are owned by the same UID. If it is
1883 // set the policy flag that we will not reveal coordinate information to this window.
1884 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1885 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001886 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 if (foregroundWindowHandle) {
1888 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001889 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001890 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1891 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1892 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001893 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1894 InputTarget::FLAG_ZERO_COORDS,
1895 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898 }
1899 }
1900 }
1901
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 // If this is the first pointer going down and the touched window has a wallpaper
1903 // then also add the touched wallpaper windows so they are locked in for the duration
1904 // of the touch gesture.
1905 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1906 // engine only supports touch events. We would need to add a mechanism similar
1907 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1908 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1909 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001910 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001911 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001912 const std::vector<sp<InputWindowHandle>> windowHandles =
1913 getWindowHandlesLocked(displayId);
1914 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001916 if (info->displayId == displayId &&
1917 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001918 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001919 .addOrUpdateWindow(windowHandle,
1920 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1921 InputTarget::
1922 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1923 InputTarget::FLAG_DISPATCH_AS_IS,
1924 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926 }
1927 }
1928 }
1929
1930 // Success! Output targets.
1931 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1932
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001933 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001938 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001939 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 }
1942
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 // Drop the outside or hover touch windows since we will not care about them
1944 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001945 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
1947Failed:
1948 // Check injection permission once and for all.
1949 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001950 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 injectionPermission = INJECTION_PERMISSION_GRANTED;
1952 } else {
1953 injectionPermission = INJECTION_PERMISSION_DENIED;
1954 }
1955 }
1956
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001957 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1958 return injectionResult;
1959 }
1960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001962 if (!wrongDevice) {
1963 if (switchedDevice) {
1964 if (DEBUG_FOCUS) {
1965 ALOGD("Conflicting pointer actions: Switched to a different device.");
1966 }
1967 *outConflictingPointerActions = true;
1968 }
1969
1970 if (isHoverAction) {
1971 // Started hovering, therefore no longer down.
1972 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001973 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001974 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1975 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 *outConflictingPointerActions = true;
1978 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001979 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001980 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1981 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001982 tempTouchState.deviceId = entry.deviceId;
1983 tempTouchState.source = entry.source;
1984 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001985 }
1986 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1987 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1988 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001989 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001990 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1991 // First pointer went down.
1992 if (oldState && oldState->down) {
1993 if (DEBUG_FOCUS) {
1994 ALOGD("Conflicting pointer actions: Down received while already down.");
1995 }
1996 *outConflictingPointerActions = true;
1997 }
1998 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1999 // One pointer went up.
2000 if (isSplit) {
2001 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2002 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002004 for (size_t i = 0; i < tempTouchState.windows.size();) {
2005 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002006 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2007 touchedWindow.pointerIds.clearBit(pointerId);
2008 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002009 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002010 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002013 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002015 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002016 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002017
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002018 // Save changes unless the action was scroll in which case the temporary touch
2019 // state was only valid for this one action.
2020 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002021 if (tempTouchState.displayId >= 0) {
2022 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07002023 } else {
2024 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002028 // Update hover state.
2029 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 }
2031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 return injectionResult;
2033}
2034
2035void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 int32_t targetFlags, BitSet32 pointerIds,
2037 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002038 std::vector<InputTarget>::iterator it =
2039 std::find_if(inputTargets.begin(), inputTargets.end(),
2040 [&windowHandle](const InputTarget& inputTarget) {
2041 return inputTarget.inputChannel->getConnectionToken() ==
2042 windowHandle->getToken();
2043 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002044
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002045 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002046
2047 if (it == inputTargets.end()) {
2048 InputTarget inputTarget;
2049 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2050 if (inputChannel == nullptr) {
2051 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2052 return;
2053 }
2054 inputTarget.inputChannel = inputChannel;
2055 inputTarget.flags = targetFlags;
2056 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2057 inputTargets.push_back(inputTarget);
2058 it = inputTargets.end() - 1;
2059 }
2060
2061 ALOG_ASSERT(it->flags == targetFlags);
2062 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2063
2064 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2065 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066}
2067
Michael Wright3dd60e22019-03-27 22:06:44 +00002068void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 int32_t displayId, float xOffset,
2070 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002071 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2072 mGlobalMonitorsByDisplay.find(displayId);
2073
2074 if (it != mGlobalMonitorsByDisplay.end()) {
2075 const std::vector<Monitor>& monitors = it->second;
2076 for (const Monitor& monitor : monitors) {
2077 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080}
2081
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002082void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2083 float yOffset,
2084 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 InputTarget target;
2086 target.inputChannel = monitor.inputChannel;
2087 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002088 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002089 inputTargets.push_back(target);
2090}
2091
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002093 const InjectionState* injectionState) {
2094 if (injectionState &&
2095 (windowHandle == nullptr ||
2096 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2097 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002098 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002100 "owned by uid %d",
2101 injectionState->injectorPid, injectionState->injectorUid,
2102 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 } else {
2104 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002105 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107 return false;
2108 }
2109 return true;
2110}
2111
Robert Carr9cada032020-04-13 17:21:08 -07002112/**
2113 * Indicate whether one window handle should be considered as obscuring
2114 * another window handle. We only check a few preconditions. Actually
2115 * checking the bounds is left to the caller.
2116 */
2117static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2118 const sp<InputWindowHandle>& otherHandle) {
2119 // Compare by token so cloned layers aren't counted
2120 if (haveSameToken(windowHandle, otherHandle)) {
2121 return false;
2122 }
2123 auto info = windowHandle->getInfo();
2124 auto otherInfo = otherHandle->getInfo();
2125 if (!otherInfo->visible) {
2126 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002127 } else if (info->ownerPid == otherInfo->ownerPid) {
2128 // If ownerPid is the same we don't generate occlusion events as there
2129 // is no in-process security boundary.
Robert Carr9cada032020-04-13 17:21:08 -07002130 return false;
2131 } else if (otherInfo->isTrustedOverlay()) {
2132 return false;
2133 } else if (otherInfo->displayId != info->displayId) {
2134 return false;
2135 }
2136 return true;
2137}
2138
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002139bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2140 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002142 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2143 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002144 if (windowHandle == otherHandle) {
2145 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002148 if (canBeObscuredBy(windowHandle, otherHandle) &&
2149 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 return true;
2151 }
2152 }
2153 return false;
2154}
2155
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002156bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2157 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002158 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002159 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002160 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002161 if (windowHandle == otherHandle) {
2162 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002163 }
2164
2165 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002166 if (canBeObscuredBy(windowHandle, otherHandle) &&
2167 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002168 return true;
2169 }
2170 }
2171 return false;
2172}
2173
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002174std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 const sp<InputApplicationHandle>& applicationHandle,
2176 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002177 if (applicationHandle != nullptr) {
2178 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002179 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 } else {
2181 return applicationHandle->getName();
2182 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002183 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002184 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002186 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
2188}
2189
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002191 if (eventEntry.type == EventEntry::Type::FOCUS) {
2192 // Focus events are passed to apps, but do not represent user activity.
2193 return;
2194 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002195 int32_t displayId = getTargetDisplayId(eventEntry);
2196 sp<InputWindowHandle> focusedWindowHandle =
2197 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2198 if (focusedWindowHandle != nullptr) {
2199 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2201#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002202 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203#endif
2204 return;
2205 }
2206 }
2207
2208 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002209 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002210 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2212 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 return;
2214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002216 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 eventType = USER_ACTIVITY_EVENT_TOUCH;
2218 }
2219 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002221 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002222 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2223 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002224 return;
2225 }
2226 eventType = USER_ACTIVITY_EVENT_BUTTON;
2227 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002229 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002230 case EventEntry::Type::CONFIGURATION_CHANGED:
2231 case EventEntry::Type::DEVICE_RESET: {
2232 LOG_ALWAYS_FATAL("%s events are not user activity",
2233 EventEntry::typeToString(eventEntry.type));
2234 break;
2235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002238 std::unique_ptr<CommandEntry> commandEntry =
2239 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002240 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002242 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243}
2244
2245void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 const sp<Connection>& connection,
2247 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002248 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002249 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002251 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002252 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002253 ATRACE_NAME(message.c_str());
2254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255#if DEBUG_DISPATCH_CYCLE
2256 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002257 "globalScaleFactor=%f, pointerIds=0x%x %s",
2258 connection->getInputChannelName().c_str(), inputTarget.flags,
2259 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2260 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261#endif
2262
2263 // Skip this event if the connection status is not normal.
2264 // We don't want to enqueue additional outbound events if the connection is broken.
2265 if (connection->status != Connection::STATUS_NORMAL) {
2266#if DEBUG_DISPATCH_CYCLE
2267 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269#endif
2270 return;
2271 }
2272
2273 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002274 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2275 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2276 "Entry type %s should not have FLAG_SPLIT",
2277 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002279 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002280 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002282 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 if (!splitMotionEntry) {
2284 return; // split event was dropped
2285 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002286 if (DEBUG_FOCUS) {
2287 ALOGD("channel '%s' ~ Split motion event.",
2288 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002289 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002290 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 splitMotionEntry->release();
2293 return;
2294 }
2295 }
2296
2297 // Not splitting. Enqueue dispatch entries for the event as is.
2298 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2299}
2300
2301void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 const sp<Connection>& connection,
2303 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002304 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002307 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002308 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 ATRACE_NAME(message.c_str());
2310 }
2311
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002312 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313
2314 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002315 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002316 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002317 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002319 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002321 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002322 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002323 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002325 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002326 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
2328 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002329 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 startDispatchCycleLocked(currentTime, connection);
2331 }
2332}
2333
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2335 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002336 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002338 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2340 connection->getInputChannelName().c_str(),
2341 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002342 ATRACE_NAME(message.c_str());
2343 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002344 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 if (!(inputTargetFlags & dispatchMode)) {
2346 return;
2347 }
2348 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2349
2350 // This is a new event.
2351 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002352 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002353 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002355 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2356 // different EventEntry than what was passed in.
2357 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002359 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002360 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002361 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002362 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002363 dispatchEntry->resolvedAction = keyEntry.action;
2364 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2367 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2370 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002372 return; // skip the inconsistent event
2373 }
2374 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002377 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002378 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002379 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2380 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2381 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2382 static_cast<int32_t>(IdGenerator::Source::OTHER);
2383 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2385 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2386 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2387 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2388 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2389 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2390 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2391 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2392 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2393 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2394 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002395 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002396 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 }
2398 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002399 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2400 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2403 "event",
2404 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002406 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002409 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2411 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2412 }
2413 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2414 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2418 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002420 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2421 "event",
2422 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002424 return; // skip the inconsistent event
2425 }
2426
Garfield Tan1c7bc862020-01-28 13:24:04 -08002427 dispatchEntry->resolvedEventId =
2428 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2429 ? mIdGenerator.nextId()
2430 : motionEntry.id;
2431 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2432 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2433 ") to MotionEvent(id=0x%" PRIx32 ").",
2434 motionEntry.id, dispatchEntry->resolvedEventId);
2435 ATRACE_NAME(message.c_str());
2436 }
2437
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002438 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002439 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002440
2441 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002443 case EventEntry::Type::FOCUS: {
2444 break;
2445 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002446 case EventEntry::Type::CONFIGURATION_CHANGED:
2447 case EventEntry::Type::DEVICE_RESET: {
2448 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002449 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002450 break;
2451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453
2454 // Remember that we are waiting for this dispatch to complete.
2455 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002456 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458
2459 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002460 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002461 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002462}
2463
chaviwfd6d3512019-03-25 13:23:49 -07002464void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002466 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002467 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2468 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002469 return;
2470 }
2471
2472 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2473 if (inputWindowHandle == nullptr) {
2474 return;
2475 }
2476
chaviw8c9cf542019-03-25 13:02:48 -07002477 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002478 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002479
2480 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2481
2482 if (!hasFocusChanged) {
2483 return;
2484 }
2485
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002486 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2487 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002488 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002489 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490}
2491
2492void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002494 if (ATRACE_ENABLED()) {
2495 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002497 ATRACE_NAME(message.c_str());
2498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501#endif
2502
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002503 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2504 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002506 const nsecs_t timeout =
2507 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2508 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509
2510 // Publish the event.
2511 status_t status;
2512 EventEntry* eventEntry = dispatchEntry->eventEntry;
2513 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002514 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002515 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2516 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002519 status =
2520 connection->inputPublisher
2521 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2522 keyEntry->deviceId, keyEntry->source,
2523 keyEntry->displayId, std::move(hmac),
2524 dispatchEntry->resolvedAction,
2525 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2526 keyEntry->scanCode, keyEntry->metaState,
2527 keyEntry->repeatCount, keyEntry->downTime,
2528 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002532 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 PointerCoords scaledCoords[MAX_POINTERS];
2536 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2537
chaviw82357092020-01-28 13:13:06 -08002538 // Set the X and Y offset and X and Y scale depending on the input source.
2539 float xOffset = 0.0f, yOffset = 0.0f;
2540 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2542 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2543 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002544 xScale = dispatchEntry->windowXScale;
2545 yScale = dispatchEntry->windowYScale;
2546 xOffset = dispatchEntry->xOffset * xScale;
2547 yOffset = dispatchEntry->yOffset * yScale;
2548 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2550 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002551 // Don't apply window scale here since we don't want scale to affect raw
2552 // coordinates. The scale will be sent back to the client and applied
2553 // later when requesting relative coordinates.
2554 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2555 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 }
2557 usingCoords = scaledCoords;
2558 }
2559 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 // We don't want the dispatch target to know.
2561 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2562 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2563 scaledCoords[i].clear();
2564 }
2565 usingCoords = scaledCoords;
2566 }
2567 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002568
2569 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570
2571 // Publish the motion event.
2572 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002573 .publishMotionEvent(dispatchEntry->seq,
2574 dispatchEntry->resolvedEventId,
2575 motionEntry->deviceId, motionEntry->source,
2576 motionEntry->displayId, std::move(hmac),
2577 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 motionEntry->actionButton,
2579 dispatchEntry->resolvedFlags,
2580 motionEntry->edgeFlags, motionEntry->metaState,
2581 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002582 motionEntry->classification, xScale, yScale,
2583 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 motionEntry->yPrecision,
2585 motionEntry->xCursorPosition,
2586 motionEntry->yCursorPosition,
2587 motionEntry->downTime, motionEntry->eventTime,
2588 motionEntry->pointerCount,
2589 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002590 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 break;
2592 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002593 case EventEntry::Type::FOCUS: {
2594 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2595 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002596 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002597 focusEntry->hasFocus,
2598 mInTouchMode);
2599 break;
2600 }
2601
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002602 case EventEntry::Type::CONFIGURATION_CHANGED:
2603 case EventEntry::Type::DEVICE_RESET: {
2604 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2605 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 }
2609
2610 // Check the result.
2611 if (status) {
2612 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002613 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002615 "This is unexpected because the wait queue is empty, so the pipe "
2616 "should be empty and we shouldn't have any problems writing an "
2617 "event to it, status=%d",
2618 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2620 } else {
2621 // Pipe is full and we are waiting for the app to finish process some events
2622 // before sending more events to it.
2623#if DEBUG_DISPATCH_CYCLE
2624 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 "waiting for the application to catch up",
2626 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 }
2629 } else {
2630 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 "status=%d",
2632 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2634 }
2635 return;
2636 }
2637
2638 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002639 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2640 connection->outboundQueue.end(),
2641 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002642 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002643 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002644 if (connection->responsive) {
2645 mAnrTracker.insert(dispatchEntry->timeoutTime,
2646 connection->inputChannel->getConnectionToken());
2647 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002648 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650}
2651
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002652const std::array<uint8_t, 32> InputDispatcher::getSignature(
2653 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2654 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2655 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2656 // Only sign events up and down events as the purely move events
2657 // are tied to their up/down counterparts so signing would be redundant.
2658 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2659 verifiedEvent.actionMasked = actionMasked;
2660 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2661 return mHmacKeyManager.sign(verifiedEvent);
2662 }
2663 return INVALID_HMAC;
2664}
2665
2666const std::array<uint8_t, 32> InputDispatcher::getSignature(
2667 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2668 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2669 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2670 verifiedEvent.action = dispatchEntry.resolvedAction;
2671 return mHmacKeyManager.sign(verifiedEvent);
2672}
2673
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 const sp<Connection>& connection, uint32_t seq,
2676 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677#if DEBUG_DISPATCH_CYCLE
2678 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680#endif
2681
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 if (connection->status == Connection::STATUS_BROKEN ||
2683 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 return;
2685 }
2686
2687 // Notify other system components and prepare to start the next dispatch cycle.
2688 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2689}
2690
2691void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 const sp<Connection>& connection,
2693 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694#if DEBUG_DISPATCH_CYCLE
2695 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697#endif
2698
2699 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002700 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002701 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002702 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002703 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704
2705 // The connection appears to be unrecoverably broken.
2706 // Ignore already broken or zombie connections.
2707 if (connection->status == Connection::STATUS_NORMAL) {
2708 connection->status = Connection::STATUS_BROKEN;
2709
2710 if (notify) {
2711 // Notify other system components.
2712 onDispatchCycleBrokenLocked(currentTime, connection);
2713 }
2714 }
2715}
2716
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002717void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2718 while (!queue.empty()) {
2719 DispatchEntry* dispatchEntry = queue.front();
2720 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002721 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 }
2723}
2724
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002725void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002727 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
2729 delete dispatchEntry;
2730}
2731
2732int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2733 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2734
2735 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002736 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002738 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 "fd=%d, events=0x%x",
2741 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 return 0; // remove the callback
2743 }
2744
2745 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002746 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2748 if (!(events & ALOOPER_EVENT_INPUT)) {
2749 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 "events=0x%x",
2751 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 return 1;
2753 }
2754
2755 nsecs_t currentTime = now();
2756 bool gotOne = false;
2757 status_t status;
2758 for (;;) {
2759 uint32_t seq;
2760 bool handled;
2761 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2762 if (status) {
2763 break;
2764 }
2765 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2766 gotOne = true;
2767 }
2768 if (gotOne) {
2769 d->runCommandsLockedInterruptible();
2770 if (status == WOULD_BLOCK) {
2771 return 1;
2772 }
2773 }
2774
2775 notify = status != DEAD_OBJECT || !connection->monitor;
2776 if (notify) {
2777 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
2780 } else {
2781 // Monitor channels are never explicitly unregistered.
2782 // We do it automatically when the remote endpoint is closed so don't warn
2783 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002784 const bool stillHaveWindowHandle =
2785 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2786 nullptr;
2787 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (notify) {
2789 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 "events=0x%x",
2791 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 }
2793 }
2794
2795 // Unregister the channel.
2796 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2797 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799}
2800
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002803 for (const auto& pair : mConnectionsByFd) {
2804 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
2806}
2807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002809 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002810 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2811 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2812}
2813
2814void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2815 const CancelationOptions& options,
2816 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2817 for (const auto& it : monitorsByDisplay) {
2818 const std::vector<Monitor>& monitors = it.second;
2819 for (const Monitor& monitor : monitors) {
2820 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002821 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002822 }
2823}
2824
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2826 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002827 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002828 if (connection == nullptr) {
2829 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002831
2832 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833}
2834
2835void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2836 const sp<Connection>& connection, const CancelationOptions& options) {
2837 if (connection->status == Connection::STATUS_BROKEN) {
2838 return;
2839 }
2840
2841 nsecs_t currentTime = now();
2842
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002843 std::vector<EventEntry*> cancelationEvents =
2844 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002846 if (cancelationEvents.empty()) {
2847 return;
2848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002850 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2851 "with reality: %s, mode=%d.",
2852 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2853 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002855
2856 InputTarget target;
2857 sp<InputWindowHandle> windowHandle =
2858 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2859 if (windowHandle != nullptr) {
2860 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2861 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2862 windowInfo->windowXScale, windowInfo->windowYScale);
2863 target.globalScaleFactor = windowInfo->globalScaleFactor;
2864 }
2865 target.inputChannel = connection->inputChannel;
2866 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2867
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002868 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2869 EventEntry* cancelationEventEntry = cancelationEvents[i];
2870 switch (cancelationEventEntry->type) {
2871 case EventEntry::Type::KEY: {
2872 logOutboundKeyDetails("cancel - ",
2873 static_cast<const KeyEntry&>(*cancelationEventEntry));
2874 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002876 case EventEntry::Type::MOTION: {
2877 logOutboundMotionDetails("cancel - ",
2878 static_cast<const MotionEntry&>(*cancelationEventEntry));
2879 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002881 case EventEntry::Type::FOCUS: {
2882 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2883 break;
2884 }
2885 case EventEntry::Type::CONFIGURATION_CHANGED:
2886 case EventEntry::Type::DEVICE_RESET: {
2887 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2888 EventEntry::typeToString(cancelationEventEntry->type));
2889 break;
2890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 }
2892
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002893 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2894 target, InputTarget::FLAG_DISPATCH_AS_IS);
2895
2896 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002898
2899 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900}
2901
Svet Ganov5d3bc372020-01-26 23:11:07 -08002902void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2903 const sp<Connection>& connection) {
2904 if (connection->status == Connection::STATUS_BROKEN) {
2905 return;
2906 }
2907
2908 nsecs_t currentTime = now();
2909
2910 std::vector<EventEntry*> downEvents =
2911 connection->inputState.synthesizePointerDownEvents(currentTime);
2912
2913 if (downEvents.empty()) {
2914 return;
2915 }
2916
2917#if DEBUG_OUTBOUND_EVENT_DETAILS
2918 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2919 connection->getInputChannelName().c_str(), downEvents.size());
2920#endif
2921
2922 InputTarget target;
2923 sp<InputWindowHandle> windowHandle =
2924 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2925 if (windowHandle != nullptr) {
2926 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2927 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2928 windowInfo->windowXScale, windowInfo->windowYScale);
2929 target.globalScaleFactor = windowInfo->globalScaleFactor;
2930 }
2931 target.inputChannel = connection->inputChannel;
2932 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2933
2934 for (EventEntry* downEventEntry : downEvents) {
2935 switch (downEventEntry->type) {
2936 case EventEntry::Type::MOTION: {
2937 logOutboundMotionDetails("down - ",
2938 static_cast<const MotionEntry&>(*downEventEntry));
2939 break;
2940 }
2941
2942 case EventEntry::Type::KEY:
2943 case EventEntry::Type::FOCUS:
2944 case EventEntry::Type::CONFIGURATION_CHANGED:
2945 case EventEntry::Type::DEVICE_RESET: {
2946 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2947 EventEntry::typeToString(downEventEntry->type));
2948 break;
2949 }
2950 }
2951
2952 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2953 target, InputTarget::FLAG_DISPATCH_AS_IS);
2954
2955 downEventEntry->release();
2956 }
2957
2958 startDispatchCycleLocked(currentTime, connection);
2959}
2960
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002961MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002962 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 ALOG_ASSERT(pointerIds.value != 0);
2964
2965 uint32_t splitPointerIndexMap[MAX_POINTERS];
2966 PointerProperties splitPointerProperties[MAX_POINTERS];
2967 PointerCoords splitPointerCoords[MAX_POINTERS];
2968
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 uint32_t splitPointerCount = 0;
2971
2972 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 uint32_t pointerId = uint32_t(pointerProperties.id);
2977 if (pointerIds.hasBit(pointerId)) {
2978 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2979 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2980 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002981 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 splitPointerCount += 1;
2983 }
2984 }
2985
2986 if (splitPointerCount != pointerIds.count()) {
2987 // This is bad. We are missing some of the pointers that we expected to deliver.
2988 // Most likely this indicates that we received an ACTION_MOVE events that has
2989 // different pointer ids than we expected based on the previous ACTION_DOWN
2990 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2991 // in this way.
2992 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 "we expected there to be %d pointers. This probably means we received "
2994 "a broken sequence of pointer ids from the input device.",
2995 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002996 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 }
2998
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002999 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3002 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3004 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003005 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 uint32_t pointerId = uint32_t(pointerProperties.id);
3007 if (pointerIds.hasBit(pointerId)) {
3008 if (pointerIds.count() == 1) {
3009 // The first/last pointer went down/up.
3010 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 ? AMOTION_EVENT_ACTION_DOWN
3012 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 } else {
3014 // A secondary pointer went down/up.
3015 uint32_t splitPointerIndex = 0;
3016 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3017 splitPointerIndex += 1;
3018 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003019 action = maskedAction |
3020 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
3022 } else {
3023 // An unrelated pointer changed.
3024 action = AMOTION_EVENT_ACTION_MOVE;
3025 }
3026 }
3027
Garfield Tan1c7bc862020-01-28 13:24:04 -08003028 int32_t newId = mIdGenerator.nextId();
3029 if (ATRACE_ENABLED()) {
3030 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3031 ") to MotionEvent(id=0x%" PRIx32 ").",
3032 originalMotionEntry.id, newId);
3033 ATRACE_NAME(message.c_str());
3034 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003035 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003036 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3037 originalMotionEntry.source, originalMotionEntry.displayId,
3038 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 originalMotionEntry.actionButton, originalMotionEntry.flags,
3040 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3041 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3042 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3043 originalMotionEntry.xCursorPosition,
3044 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003045 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003047 if (originalMotionEntry.injectionState) {
3048 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 splitMotionEntry->injectionState->refCount += 1;
3050 }
3051
3052 return splitMotionEntry;
3053}
3054
3055void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3056#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003057 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058#endif
3059
3060 bool needWake;
3061 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003062 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Prabir Pradhan42611e02018-11-27 14:04:02 -08003064 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003065 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 needWake = enqueueInboundEventLocked(newEntry);
3067 } // release lock
3068
3069 if (needWake) {
3070 mLooper->wake();
3071 }
3072}
3073
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003074/**
3075 * If one of the meta shortcuts is detected, process them here:
3076 * Meta + Backspace -> generate BACK
3077 * Meta + Enter -> generate HOME
3078 * This will potentially overwrite keyCode and metaState.
3079 */
3080void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003082 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3083 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3084 if (keyCode == AKEYCODE_DEL) {
3085 newKeyCode = AKEYCODE_BACK;
3086 } else if (keyCode == AKEYCODE_ENTER) {
3087 newKeyCode = AKEYCODE_HOME;
3088 }
3089 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003090 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003091 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003092 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003093 keyCode = newKeyCode;
3094 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3095 }
3096 } else if (action == AKEY_EVENT_ACTION_UP) {
3097 // In order to maintain a consistent stream of up and down events, check to see if the key
3098 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3099 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003100 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003101 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003102 auto replacementIt = mReplacedKeys.find(replacement);
3103 if (replacementIt != mReplacedKeys.end()) {
3104 keyCode = replacementIt->second;
3105 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003106 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3107 }
3108 }
3109}
3110
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3112#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3114 "policyFlags=0x%x, action=0x%x, "
3115 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3116 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3117 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3118 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119#endif
3120 if (!validateKeyEvent(args->action)) {
3121 return;
3122 }
3123
3124 uint32_t policyFlags = args->policyFlags;
3125 int32_t flags = args->flags;
3126 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003127 // InputDispatcher tracks and generates key repeats on behalf of
3128 // whatever notifies it, so repeatCount should always be set to 0
3129 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3131 policyFlags |= POLICY_FLAG_VIRTUAL;
3132 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 if (policyFlags & POLICY_FLAG_FUNCTION) {
3135 metaState |= AMETA_FUNCTION_ON;
3136 }
3137
3138 policyFlags |= POLICY_FLAG_TRUSTED;
3139
Michael Wright78f24442014-08-06 15:55:28 -07003140 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003141 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003142
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003144 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003145 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3146 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147
Michael Wright2b3c3302018-03-02 17:19:13 +00003148 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003150 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3151 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 bool needWake;
3156 { // acquire lock
3157 mLock.lock();
3158
3159 if (shouldSendKeyToInputFilterLocked(args)) {
3160 mLock.unlock();
3161
3162 policyFlags |= POLICY_FLAG_FILTERED;
3163 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3164 return; // event was consumed by the filter
3165 }
3166
3167 mLock.lock();
3168 }
3169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003171 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 args->displayId, policyFlags, args->action, flags, keyCode,
3173 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
3175 needWake = enqueueInboundEventLocked(newEntry);
3176 mLock.unlock();
3177 } // release lock
3178
3179 if (needWake) {
3180 mLooper->wake();
3181 }
3182}
3183
3184bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3185 return mInputFilterEnabled;
3186}
3187
3188void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3189#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003190 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3191 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003192 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3193 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003194 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003195 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3196 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3197 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3198 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 for (uint32_t i = 0; i < args->pointerCount; i++) {
3200 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 "x=%f, y=%f, pressure=%f, size=%f, "
3202 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3203 "orientation=%f",
3204 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3205 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3206 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3207 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3208 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3209 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3210 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3211 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3212 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3213 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 }
3215#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3217 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 return;
3219 }
3220
3221 uint32_t policyFlags = args->policyFlags;
3222 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003223
3224 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003225 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003226 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3227 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230
3231 bool needWake;
3232 { // acquire lock
3233 mLock.lock();
3234
3235 if (shouldSendMotionToInputFilterLocked(args)) {
3236 mLock.unlock();
3237
3238 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003239 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3240 args->action, args->actionButton, args->flags, args->edgeFlags,
3241 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3242 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3243 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3244 args->downTime, args->eventTime, args->pointerCount,
3245 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246
3247 policyFlags |= POLICY_FLAG_FILTERED;
3248 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3249 return; // event was consumed by the filter
3250 }
3251
3252 mLock.lock();
3253 }
3254
3255 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003256 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003257 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003258 args->displayId, policyFlags, args->action, args->actionButton,
3259 args->flags, args->metaState, args->buttonState,
3260 args->classification, args->edgeFlags, args->xPrecision,
3261 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3262 args->downTime, args->pointerCount, args->pointerProperties,
3263 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264
3265 needWake = enqueueInboundEventLocked(newEntry);
3266 mLock.unlock();
3267 } // release lock
3268
3269 if (needWake) {
3270 mLooper->wake();
3271 }
3272}
3273
3274bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003275 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276}
3277
3278void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3279#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003280 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281 "switchMask=0x%08x",
3282 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283#endif
3284
3285 uint32_t policyFlags = args->policyFlags;
3286 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288}
3289
3290void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3291#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3293 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294#endif
3295
3296 bool needWake;
3297 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003298 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Prabir Pradhan42611e02018-11-27 14:04:02 -08003300 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003301 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 needWake = enqueueInboundEventLocked(newEntry);
3303 } // release lock
3304
3305 if (needWake) {
3306 mLooper->wake();
3307 }
3308}
3309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3311 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003312 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313#if DEBUG_INBOUND_EVENT_DETAILS
3314 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003315 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3316 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317#endif
3318
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003319 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320
3321 policyFlags |= POLICY_FLAG_INJECTED;
3322 if (hasInjectionPermission(injectorPid, injectorUid)) {
3323 policyFlags |= POLICY_FLAG_TRUSTED;
3324 }
3325
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003326 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003329 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3330 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 if (!validateKeyEvent(action)) {
3332 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003335 int32_t flags = incomingKey.getFlags();
3336 int32_t keyCode = incomingKey.getKeyCode();
3337 int32_t metaState = incomingKey.getMetaState();
3338 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003340 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003341 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003342 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3343 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3344 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3347 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003348 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349
3350 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3351 android::base::Timer t;
3352 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3353 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3354 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3355 std::to_string(t.duration().count()).c_str());
3356 }
3357 }
3358
3359 mLock.lock();
3360 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003361 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3362 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003363 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3364 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003365 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 injectedEntries.push(injectedEntry);
3367 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
3369
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 case AINPUT_EVENT_TYPE_MOTION: {
3371 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3372 int32_t action = motionEvent->getAction();
3373 size_t pointerCount = motionEvent->getPointerCount();
3374 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3375 int32_t actionButton = motionEvent->getActionButton();
3376 int32_t displayId = motionEvent->getDisplayId();
3377 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3378 return INPUT_EVENT_INJECTION_FAILED;
3379 }
3380
3381 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3382 nsecs_t eventTime = motionEvent->getEventTime();
3383 android::base::Timer t;
3384 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3385 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3386 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3387 std::to_string(t.duration().count()).c_str());
3388 }
3389 }
3390
3391 mLock.lock();
3392 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3393 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3394 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003395 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3396 motionEvent->getSource(), motionEvent->getDisplayId(),
3397 policyFlags, action, actionButton, motionEvent->getFlags(),
3398 motionEvent->getMetaState(), motionEvent->getButtonState(),
3399 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3400 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003401 motionEvent->getRawXCursorPosition(),
3402 motionEvent->getRawYCursorPosition(),
3403 motionEvent->getDownTime(), uint32_t(pointerCount),
3404 pointerProperties, samplePointerCoords,
3405 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 injectedEntries.push(injectedEntry);
3407 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3408 sampleEventTimes += 1;
3409 samplePointerCoords += pointerCount;
3410 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003411 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003412 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003413 motionEvent->getDisplayId(), policyFlags, action,
3414 actionButton, motionEvent->getFlags(),
3415 motionEvent->getMetaState(), motionEvent->getButtonState(),
3416 motionEvent->getClassification(),
3417 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3418 motionEvent->getYPrecision(),
3419 motionEvent->getRawXCursorPosition(),
3420 motionEvent->getRawYCursorPosition(),
3421 motionEvent->getDownTime(), uint32_t(pointerCount),
3422 pointerProperties, samplePointerCoords,
3423 motionEvent->getXOffset(), motionEvent->getYOffset());
3424 injectedEntries.push(nextInjectedEntry);
3425 }
3426 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003430 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433
3434 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3435 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3436 injectionState->injectionIsAsync = true;
3437 }
3438
3439 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003440 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441
3442 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003443 while (!injectedEntries.empty()) {
3444 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3445 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
3447
3448 mLock.unlock();
3449
3450 if (needWake) {
3451 mLooper->wake();
3452 }
3453
3454 int32_t injectionResult;
3455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003456 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
3458 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3459 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3460 } else {
3461 for (;;) {
3462 injectionResult = injectionState->injectionResult;
3463 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3464 break;
3465 }
3466
3467 nsecs_t remainingTimeout = endTime - now();
3468 if (remainingTimeout <= 0) {
3469#if DEBUG_INJECTION
3470 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472#endif
3473 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3474 break;
3475 }
3476
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003477 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 }
3479
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3481 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 while (injectionState->pendingForegroundDispatches != 0) {
3483#if DEBUG_INJECTION
3484 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486#endif
3487 nsecs_t remainingTimeout = endTime - now();
3488 if (remainingTimeout <= 0) {
3489#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3491 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492#endif
3493 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3494 break;
3495 }
3496
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003497 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 }
3499 }
3500 }
3501
3502 injectionState->release();
3503 } // release lock
3504
3505#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003506 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508#endif
3509
3510 return injectionResult;
3511}
3512
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003513std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003514 std::array<uint8_t, 32> calculatedHmac;
3515 std::unique_ptr<VerifiedInputEvent> result;
3516 switch (event.getType()) {
3517 case AINPUT_EVENT_TYPE_KEY: {
3518 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3519 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3520 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3521 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3522 break;
3523 }
3524 case AINPUT_EVENT_TYPE_MOTION: {
3525 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3526 VerifiedMotionEvent verifiedMotionEvent =
3527 verifiedMotionEventFromMotionEvent(motionEvent);
3528 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3529 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3530 break;
3531 }
3532 default: {
3533 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3534 return nullptr;
3535 }
3536 }
3537 if (calculatedHmac == INVALID_HMAC) {
3538 return nullptr;
3539 }
3540 if (calculatedHmac != event.getHmac()) {
3541 return nullptr;
3542 }
3543 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003544}
3545
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003547 return injectorUid == 0 ||
3548 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549}
3550
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003551void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 InjectionState* injectionState = entry->injectionState;
3553 if (injectionState) {
3554#if DEBUG_INJECTION
3555 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003556 "injectorPid=%d, injectorUid=%d",
3557 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558#endif
3559
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 // Log the outcome since the injector did not wait for the injection result.
3562 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 case INPUT_EVENT_INJECTION_SUCCEEDED:
3564 ALOGV("Asynchronous input event injection succeeded.");
3565 break;
3566 case INPUT_EVENT_INJECTION_FAILED:
3567 ALOGW("Asynchronous input event injection failed.");
3568 break;
3569 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3570 ALOGW("Asynchronous input event injection permission denied.");
3571 break;
3572 case INPUT_EVENT_INJECTION_TIMED_OUT:
3573 ALOGW("Asynchronous input event injection timed out.");
3574 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576 }
3577
3578 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003579 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 }
3581}
3582
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003583void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 InjectionState* injectionState = entry->injectionState;
3585 if (injectionState) {
3586 injectionState->pendingForegroundDispatches += 1;
3587 }
3588}
3589
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003590void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 InjectionState* injectionState = entry->injectionState;
3592 if (injectionState) {
3593 injectionState->pendingForegroundDispatches -= 1;
3594
3595 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003596 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598 }
3599}
3600
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003601std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3602 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003603 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003604}
3605
Siarhei Vishniakou265ab012020-09-08 19:43:33 -05003606sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3607 return getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3608}
3609
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003611 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003612 if (windowHandleToken == nullptr) {
3613 return nullptr;
3614 }
3615
Arthur Hungb92218b2018-08-14 12:00:21 +08003616 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003617 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3618 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003619 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003620 return windowHandle;
3621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003624 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625}
3626
Mady Mellor017bcd12020-06-23 19:12:00 +00003627bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3628 for (auto& it : mWindowHandlesByDisplay) {
3629 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3630 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003631 if (handle->getId() == windowHandle->getId() &&
3632 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003633 if (windowHandle->getInfo()->displayId != it.first) {
3634 ALOGE("Found window %s in display %" PRId32
3635 ", but it should belong to display %" PRId32,
3636 windowHandle->getName().c_str(), it.first,
3637 windowHandle->getInfo()->displayId);
3638 }
3639 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
3642 }
3643 return false;
3644}
3645
Robert Carr5c8a0262018-10-03 16:30:44 -07003646sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3647 size_t count = mInputChannelsByToken.count(token);
3648 if (count == 0) {
3649 return nullptr;
3650 }
3651 return mInputChannelsByToken.at(token);
3652}
3653
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003654void InputDispatcher::updateWindowHandlesForDisplayLocked(
3655 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3656 if (inputWindowHandles.empty()) {
3657 // Remove all handles on a display if there are no windows left.
3658 mWindowHandlesByDisplay.erase(displayId);
3659 return;
3660 }
3661
3662 // Since we compare the pointer of input window handles across window updates, we need
3663 // to make sure the handle object for the same window stays unchanged across updates.
3664 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003665 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003666 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003667 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003668 }
3669
3670 std::vector<sp<InputWindowHandle>> newHandles;
3671 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3672 if (!handle->updateInfo()) {
3673 // handle no longer valid
3674 continue;
3675 }
3676
3677 const InputWindowInfo* info = handle->getInfo();
3678 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3679 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3680 const bool noInputChannel =
3681 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3682 const bool canReceiveInput =
3683 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3684 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3685 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003686 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003687 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003688 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003689 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003690 }
3691
3692 if (info->displayId != displayId) {
3693 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3694 handle->getName().c_str(), displayId, info->displayId);
3695 continue;
3696 }
3697
Robert Carredd13602020-04-13 17:24:34 -07003698 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3699 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003700 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003701 oldHandle->updateFrom(handle);
3702 newHandles.push_back(oldHandle);
3703 } else {
3704 newHandles.push_back(handle);
3705 }
3706 }
3707
3708 // Insert or replace
3709 mWindowHandlesByDisplay[displayId] = newHandles;
3710}
3711
Arthur Hung72d8dc32020-03-28 00:48:39 +00003712void InputDispatcher::setInputWindows(
3713 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3714 { // acquire lock
3715 std::scoped_lock _l(mLock);
3716 for (auto const& i : handlesPerDisplay) {
3717 setInputWindowsLocked(i.second, i.first);
3718 }
3719 }
3720 // Wake up poll loop since it may need to make new input dispatching choices.
3721 mLooper->wake();
3722}
3723
Arthur Hungb92218b2018-08-14 12:00:21 +08003724/**
3725 * Called from InputManagerService, update window handle list by displayId that can receive input.
3726 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3727 * If set an empty list, remove all handles from the specific display.
3728 * For focused handle, check if need to change and send a cancel event to previous one.
3729 * For removed handle, check if need to send a cancel event if already in touch.
3730 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003731void InputDispatcher::setInputWindowsLocked(
3732 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003733 if (DEBUG_FOCUS) {
3734 std::string windowList;
3735 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3736 windowList += iwh->getName() + " ";
3737 }
3738 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740
Arthur Hung72d8dc32020-03-28 00:48:39 +00003741 // Copy old handles for release if they are no longer present.
3742 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743
Arthur Hung72d8dc32020-03-28 00:48:39 +00003744 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003745
Arthur Hung72d8dc32020-03-28 00:48:39 +00003746 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3747 bool foundHoveredWindow = false;
3748 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3749 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3750 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3751 windowHandle->getInfo()->visible) {
3752 newFocusedWindowHandle = windowHandle;
3753 }
3754 if (windowHandle == mLastHoverWindowHandle) {
3755 foundHoveredWindow = true;
3756 }
3757 }
3758
3759 if (!foundHoveredWindow) {
3760 mLastHoverWindowHandle = nullptr;
3761 }
3762
3763 sp<InputWindowHandle> oldFocusedWindowHandle =
3764 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3765
3766 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3767 if (oldFocusedWindowHandle != nullptr) {
3768 if (DEBUG_FOCUS) {
3769 ALOGD("Focus left window: %s in display %" PRId32,
3770 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003771 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772 sp<InputChannel> focusedInputChannel =
3773 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3774 if (focusedInputChannel != nullptr) {
3775 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3776 "focus left window");
3777 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3778 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003779 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003780 mFocusedWindowHandlesByDisplay.erase(displayId);
3781 }
3782 if (newFocusedWindowHandle != nullptr) {
3783 if (DEBUG_FOCUS) {
3784 ALOGD("Focus entered window: %s in display %" PRId32,
3785 newFocusedWindowHandle->getName().c_str(), displayId);
3786 }
3787 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3788 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
3790
Arthur Hung72d8dc32020-03-28 00:48:39 +00003791 if (mFocusedDisplayId == displayId) {
3792 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003796 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3797 mTouchStatesByDisplay.find(displayId);
3798 if (stateIt != mTouchStatesByDisplay.end()) {
3799 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003800 for (size_t i = 0; i < state.windows.size();) {
3801 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003802 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003803 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003804 ALOGD("Touched window was removed: %s in display %" PRId32,
3805 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003806 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003807 sp<InputChannel> touchedInputChannel =
3808 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3809 if (touchedInputChannel != nullptr) {
3810 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3811 "touched window was removed");
3812 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003814 state.windows.erase(state.windows.begin() + i);
3815 } else {
3816 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
3818 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003819 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003820
Arthur Hung72d8dc32020-03-28 00:48:39 +00003821 // Release information for windows that are no longer present.
3822 // This ensures that unused input channels are released promptly.
3823 // Otherwise, they might stick around until the window handle is destroyed
3824 // which might not happen until the next GC.
3825 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003826 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003827 if (DEBUG_FOCUS) {
3828 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003829 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003830 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003831 }
chaviw291d88a2019-02-14 10:33:58 -08003832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833}
3834
3835void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003836 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003837 if (DEBUG_FOCUS) {
3838 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3839 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003842 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
Tiger Huang721e26f2018-07-24 22:26:19 +08003844 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3845 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003846
3847 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3848 inputApplicationHandle != oldFocusedApplicationHandle) {
3849 resetNoFocusedWindowTimeoutLocked();
3850 }
3851
Yi Kong9b14ac62018-07-17 13:48:38 -07003852 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003853 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003854 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003856 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003857 oldFocusedApplicationHandle.clear();
3858 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 } // release lock
3861
3862 // Wake up poll loop since it may need to make new input dispatching choices.
3863 mLooper->wake();
3864}
3865
Tiger Huang721e26f2018-07-24 22:26:19 +08003866/**
3867 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3868 * the display not specified.
3869 *
3870 * We track any unreleased events for each window. If a window loses the ability to receive the
3871 * released event, we will send a cancel event to it. So when the focused display is changed, we
3872 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3873 * display. The display-specified events won't be affected.
3874 */
3875void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003876 if (DEBUG_FOCUS) {
3877 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3878 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003879 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003880 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003881
3882 if (mFocusedDisplayId != displayId) {
3883 sp<InputWindowHandle> oldFocusedWindowHandle =
3884 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3885 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003886 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003887 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003888 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003889 CancelationOptions
3890 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3891 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003892 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003893 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3894 }
3895 }
3896 mFocusedDisplayId = displayId;
3897
3898 // Sanity check
3899 sp<InputWindowHandle> newFocusedWindowHandle =
3900 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003901 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003902
Tiger Huang721e26f2018-07-24 22:26:19 +08003903 if (newFocusedWindowHandle == nullptr) {
3904 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3905 if (!mFocusedWindowHandlesByDisplay.empty()) {
3906 ALOGE("But another display has a focused window:");
3907 for (auto& it : mFocusedWindowHandlesByDisplay) {
3908 const int32_t displayId = it.first;
3909 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003910 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3911 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003912 }
3913 }
3914 }
3915 }
3916
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003917 if (DEBUG_FOCUS) {
3918 logDispatchStateLocked();
3919 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003920 } // release lock
3921
3922 // Wake up poll loop since it may need to make new input dispatching choices.
3923 mLooper->wake();
3924}
3925
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003927 if (DEBUG_FOCUS) {
3928 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930
3931 bool changed;
3932 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003933 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
3935 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3936 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003937 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 }
3939
3940 if (mDispatchEnabled && !enabled) {
3941 resetAndDropEverythingLocked("dispatcher is being disabled");
3942 }
3943
3944 mDispatchEnabled = enabled;
3945 mDispatchFrozen = frozen;
3946 changed = true;
3947 } else {
3948 changed = false;
3949 }
3950
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003951 if (DEBUG_FOCUS) {
3952 logDispatchStateLocked();
3953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 } // release lock
3955
3956 if (changed) {
3957 // Wake up poll loop since it may need to make new input dispatching choices.
3958 mLooper->wake();
3959 }
3960}
3961
3962void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003963 if (DEBUG_FOCUS) {
3964 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
3967 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003968 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
3970 if (mInputFilterEnabled == enabled) {
3971 return;
3972 }
3973
3974 mInputFilterEnabled = enabled;
3975 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3976 } // release lock
3977
3978 // Wake up poll loop since there might be work to do to drop everything.
3979 mLooper->wake();
3980}
3981
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003982void InputDispatcher::setInTouchMode(bool inTouchMode) {
3983 std::scoped_lock lock(mLock);
3984 mInTouchMode = inTouchMode;
3985}
3986
chaviwfbe5d9c2018-12-26 12:23:37 -08003987bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3988 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003989 if (DEBUG_FOCUS) {
3990 ALOGD("Trivial transfer to same window.");
3991 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003992 return true;
3993 }
3994
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003996 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
chaviwfbe5d9c2018-12-26 12:23:37 -08003998 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3999 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004000 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004001 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 return false;
4003 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004004 if (DEBUG_FOCUS) {
4005 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4006 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004009 if (DEBUG_FOCUS) {
4010 ALOGD("Cannot transfer focus because windows are on different displays.");
4011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 return false;
4013 }
4014
4015 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004016 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4017 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004018 for (size_t i = 0; i < state.windows.size(); i++) {
4019 const TouchedWindow& touchedWindow = state.windows[i];
4020 if (touchedWindow.windowHandle == fromWindowHandle) {
4021 int32_t oldTargetFlags = touchedWindow.targetFlags;
4022 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004024 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004026 int32_t newTargetFlags = oldTargetFlags &
4027 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4028 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004029 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
Jeff Brownf086ddb2014-02-11 14:28:48 -08004031 found = true;
4032 goto Found;
4033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 }
4035 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004039 if (DEBUG_FOCUS) {
4040 ALOGD("Focus transfer failed because from window did not have focus.");
4041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 return false;
4043 }
4044
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004045 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4046 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004047 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004048 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 CancelationOptions
4050 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4051 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004053 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
4055
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004056 if (DEBUG_FOCUS) {
4057 logDispatchStateLocked();
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 } // release lock
4060
4061 // Wake up poll loop since it may need to make new input dispatching choices.
4062 mLooper->wake();
4063 return true;
4064}
4065
4066void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004067 if (DEBUG_FOCUS) {
4068 ALOGD("Resetting and dropping all events (%s).", reason);
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
4071 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4072 synthesizeCancelationEventsForAllConnectionsLocked(options);
4073
4074 resetKeyRepeatLocked();
4075 releasePendingEventLocked();
4076 drainInboundQueueLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004077 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004079 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004080 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004082 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083}
4084
4085void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004086 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 dumpDispatchStateLocked(dump);
4088
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 std::istringstream stream(dump);
4090 std::string line;
4091
4092 while (std::getline(stream, line, '\n')) {
4093 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 }
4095}
4096
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004097void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004098 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4099 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4100 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004101 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102
Tiger Huang721e26f2018-07-24 22:26:19 +08004103 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4104 dump += StringPrintf(INDENT "FocusedApplications:\n");
4105 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4106 const int32_t displayId = it.first;
4107 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004109 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004111 ns2ms(applicationHandle
4112 ->getDispatchingTimeout(
4113 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4114 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004117 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004119
4120 if (!mFocusedWindowHandlesByDisplay.empty()) {
4121 dump += StringPrintf(INDENT "FocusedWindows:\n");
4122 for (auto& it : mFocusedWindowHandlesByDisplay) {
4123 const int32_t displayId = it.first;
4124 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4126 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004127 }
4128 } else {
4129 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004132 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004134 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4135 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004136 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 state.displayId, toString(state.down), toString(state.split),
4138 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004139 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004141 for (size_t i = 0; i < state.windows.size(); i++) {
4142 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 dump += StringPrintf(INDENT4
4144 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4145 i, touchedWindow.windowHandle->getName().c_str(),
4146 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004147 }
4148 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004150 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004151 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004152 dump += INDENT3 "Portal windows:\n";
4153 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004154 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4156 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004157 }
4158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
4160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004161 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
4163
Arthur Hungb92218b2018-08-14 12:00:21 +08004164 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004166 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004167 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004168 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004169 dump += INDENT2 "Windows:\n";
4170 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004171 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004172 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Arthur Hungb92218b2018-08-14 12:00:21 +08004174 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004176 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4177 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004179 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 i, windowInfo->name.c_str(), windowInfo->displayId,
4181 windowInfo->portalToDisplayId,
4182 toString(windowInfo->paused),
4183 toString(windowInfo->hasFocus),
4184 toString(windowInfo->hasWallpaper),
4185 toString(windowInfo->visible),
4186 toString(windowInfo->canReceiveKeys),
4187 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004188 windowInfo->layoutParamsType, windowInfo->frameLeft,
4189 windowInfo->frameTop, windowInfo->frameRight,
4190 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4191 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004192 dumpRegion(dump, windowInfo->touchableRegion);
4193 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004194 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4195 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004197 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004198 }
4199 } else {
4200 dump += INDENT2 "Windows: <none>\n";
4201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004204 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 }
4206
Michael Wright3dd60e22019-03-27 22:06:44 +00004207 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004209 const std::vector<Monitor>& monitors = it.second;
4210 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4211 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 }
4213 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004214 const std::vector<Monitor>& monitors = it.second;
4215 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4216 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004219 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221
4222 nsecs_t currentTime = now();
4223
4224 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004225 if (!mRecentQueue.empty()) {
4226 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4227 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004230 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
4235
4236 // Dump event currently being dispatched.
4237 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004238 dump += INDENT "PendingEvent:\n";
4239 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004241 dump += StringPrintf(", age=%" PRId64 "ms\n",
4242 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
4246
4247 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004248 if (!mInboundQueue.empty()) {
4249 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4250 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004253 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 }
4255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 }
4258
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004259 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004261 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4262 const KeyReplacement& replacement = pair.first;
4263 int32_t newKeyCode = pair.second;
4264 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004266 }
4267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004268 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004269 }
4270
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004271 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004273 for (const auto& pair : mConnectionsByFd) {
4274 const sp<Connection>& connection = pair.second;
4275 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004276 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004277 pair.first, connection->getInputChannelName().c_str(),
4278 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004279 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004281 if (!connection->outboundQueue.empty()) {
4282 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4283 connection->outboundQueue.size());
4284 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 dump.append(INDENT4);
4286 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004287 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4288 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004290 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004293 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004296 if (!connection->waitQueue.empty()) {
4297 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4298 connection->waitQueue.size());
4299 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004300 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004303 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004305 ns2ms(currentTime - entry->eventEntry->eventTime),
4306 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004309 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
4312 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004313 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315
4316 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004317 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4318 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004320 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004323 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004324 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4325 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4326 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327}
4328
Michael Wright3dd60e22019-03-27 22:06:44 +00004329void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4330 const size_t numMonitors = monitors.size();
4331 for (size_t i = 0; i < numMonitors; i++) {
4332 const Monitor& monitor = monitors[i];
4333 const sp<InputChannel>& channel = monitor.inputChannel;
4334 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4335 dump += "\n";
4336 }
4337}
4338
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004339status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004341 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342#endif
4343
4344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004345 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004346 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004347 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004349 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 return BAD_VALUE;
4351 }
4352
Garfield Tan1c7bc862020-01-28 13:24:04 -08004353 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
4355 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004356 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004357 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4360 } // release lock
4361
4362 // Wake the looper because some connections have changed.
4363 mLooper->wake();
4364 return OK;
4365}
4366
Michael Wright3dd60e22019-03-27 22:06:44 +00004367status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004369 { // acquire lock
4370 std::scoped_lock _l(mLock);
4371
4372 if (displayId < 0) {
4373 ALOGW("Attempted to register input monitor without a specified display.");
4374 return BAD_VALUE;
4375 }
4376
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004377 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004378 ALOGW("Attempted to register input monitor without an identifying token.");
4379 return BAD_VALUE;
4380 }
4381
Garfield Tan1c7bc862020-01-28 13:24:04 -08004382 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004383
4384 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004385 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004386 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004387
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 auto& monitorsByDisplay =
4389 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004390 monitorsByDisplay[displayId].emplace_back(inputChannel);
4391
4392 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004393 }
4394 // Wake the looper because some connections have changed.
4395 mLooper->wake();
4396 return OK;
4397}
4398
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4400#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004401 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402#endif
4403
4404 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004405 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
4407 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4408 if (status) {
4409 return status;
4410 }
4411 } // release lock
4412
4413 // Wake the poll loop because removing the connection may have changed the current
4414 // synchronization state.
4415 mLooper->wake();
4416 return OK;
4417}
4418
4419status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004421 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004422 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 return BAD_VALUE;
4426 }
4427
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004428 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004429 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004430
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 if (connection->monitor) {
4432 removeMonitorChannelLocked(inputChannel);
4433 }
4434
4435 mLooper->removeFd(inputChannel->getFd());
4436
4437 nsecs_t currentTime = now();
4438 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4439
4440 connection->status = Connection::STATUS_ZOMBIE;
4441 return OK;
4442}
4443
4444void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004445 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4446 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4447}
4448
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449void InputDispatcher::removeMonitorChannelLocked(
4450 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004451 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004453 std::vector<Monitor>& monitors = it->second;
4454 const size_t numMonitors = monitors.size();
4455 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004456 if (monitors[i].inputChannel == inputChannel) {
4457 monitors.erase(monitors.begin() + i);
4458 break;
4459 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004460 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004461 if (monitors.empty()) {
4462 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004463 } else {
4464 ++it;
4465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467}
4468
Michael Wright3dd60e22019-03-27 22:06:44 +00004469status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4470 { // acquire lock
4471 std::scoped_lock _l(mLock);
4472 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4473
4474 if (!foundDisplayId) {
4475 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4476 return BAD_VALUE;
4477 }
4478 int32_t displayId = foundDisplayId.value();
4479
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004480 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4481 mTouchStatesByDisplay.find(displayId);
4482 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004483 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4484 return BAD_VALUE;
4485 }
4486
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004487 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004488 std::optional<int32_t> foundDeviceId;
4489 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004490 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004491 foundDeviceId = state.deviceId;
4492 }
4493 }
4494 if (!foundDeviceId || !state.down) {
4495 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004497 return BAD_VALUE;
4498 }
4499 int32_t deviceId = foundDeviceId.value();
4500
4501 // Send cancel events to all the input channels we're stealing from.
4502 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004504 options.deviceId = deviceId;
4505 options.displayId = displayId;
4506 for (const TouchedWindow& window : state.windows) {
4507 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004508 if (channel != nullptr) {
4509 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4510 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004511 }
4512 // Then clear the current touch state so we stop dispatching to them as well.
4513 state.filterNonMonitors();
4514 }
4515 return OK;
4516}
4517
Michael Wright3dd60e22019-03-27 22:06:44 +00004518std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4519 const sp<IBinder>& token) {
4520 for (const auto& it : mGestureMonitorsByDisplay) {
4521 const std::vector<Monitor>& monitors = it.second;
4522 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004523 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004524 return it.first;
4525 }
4526 }
4527 }
4528 return std::nullopt;
4529}
4530
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004531sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004532 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004533 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004534 }
4535
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004536 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004537 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004538 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004539 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 }
4541 }
Robert Carr4e670e52018-08-15 13:26:12 -07004542
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004543 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544}
4545
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004546void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004547 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004548 removeByValue(mConnectionsByFd, connection);
4549}
4550
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004551void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4552 const sp<Connection>& connection, uint32_t seq,
4553 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004554 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4555 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 commandEntry->connection = connection;
4557 commandEntry->eventTime = currentTime;
4558 commandEntry->seq = seq;
4559 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004560 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561}
4562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4564 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004566 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004568 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4569 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004571 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
chaviw0c06c6e2019-01-09 13:27:07 -08004574void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004576 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4577 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004578 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4579 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004580 commandEntry->oldToken = oldToken;
4581 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004582 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004583}
4584
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004585void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004586 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4587 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004588 if (connection.waitQueue.empty()) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004589 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004590 connection.inputChannel->getName().c_str());
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004591 return;
4592 }
4593 /**
4594 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4595 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4596 * has changed. This could cause newer entries to time out before the already dispatched
4597 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4598 * processes the events linearly. So providing information about the oldest entry seems to be
4599 * most useful.
4600 */
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004601 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004602 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4603 std::string reason =
4604 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004605 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004606 ns2ms(currentWait),
4607 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004609 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004610 reason);
4611
4612 std::unique_ptr<CommandEntry> commandEntry =
4613 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4614 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004615 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004616 commandEntry->reason = std::move(reason);
4617 postCommandLocked(std::move(commandEntry));
4618}
4619
4620void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4621 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4622 application->getName().c_str());
4623
4624 updateLastAnrStateLocked(application, reason);
4625
4626 std::unique_ptr<CommandEntry> commandEntry =
4627 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4628 commandEntry->inputApplicationHandle = application;
4629 commandEntry->inputChannel = nullptr;
4630 commandEntry->reason = std::move(reason);
4631 postCommandLocked(std::move(commandEntry));
4632}
4633
4634void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4635 const std::string& reason) {
4636 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4637 updateLastAnrStateLocked(windowLabel, reason);
4638}
4639
4640void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4641 const std::string& reason) {
4642 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4643 updateLastAnrStateLocked(windowLabel, reason);
4644}
4645
4646void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4647 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004649 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 struct tm tm;
4651 localtime_r(&t, &tm);
4652 char timestr[64];
4653 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004654 mLastAnrState.clear();
4655 mLastAnrState += INDENT "ANR:\n";
4656 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004657 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4658 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004659 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660}
4661
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004662void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 mLock.unlock();
4664
4665 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4666
4667 mLock.lock();
4668}
4669
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004670void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 sp<Connection> connection = commandEntry->connection;
4672
4673 if (connection->status != Connection::STATUS_ZOMBIE) {
4674 mLock.unlock();
4675
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004676 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677
4678 mLock.lock();
4679 }
4680}
4681
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004683 sp<IBinder> oldToken = commandEntry->oldToken;
4684 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004685 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004686 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004687 mLock.lock();
4688}
4689
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004690void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004691 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004692 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 mLock.unlock();
4694
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004695 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004696 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697
4698 mLock.lock();
4699
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004700 if (timeoutExtension > 0) {
4701 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4702 } else {
4703 // stop waking up for events in this connection, it is already not responding
4704 sp<Connection> connection = getConnectionLocked(token);
4705 if (connection == nullptr) {
4706 return;
4707 }
4708 cancelEventsForAnrLocked(connection);
4709 }
4710}
4711
4712void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4713 const sp<IBinder>& connectionToken,
4714 nsecs_t timeoutExtension) {
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004715 if (connectionToken == nullptr && application != nullptr) {
4716 // The ANR happened because there's no focused window
4717 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4718 mAwaitedFocusedApplication = application;
4719 }
4720
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004721 sp<Connection> connection = getConnectionLocked(connectionToken);
4722 if (connection == nullptr) {
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004723 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004724 return;
4725 }
4726
4727 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4728 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4729
4730 connection->responsive = true;
4731 const nsecs_t newTimeout = now() + timeoutExtension;
4732 for (DispatchEntry* entry : connection->waitQueue) {
4733 if (newTimeout >= entry->timeoutTime) {
4734 // Already removed old entries when connection was marked unresponsive
4735 entry->timeoutTime = newTimeout;
4736 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4737 }
4738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739}
4740
4741void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4742 CommandEntry* commandEntry) {
4743 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004744 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
4746 mLock.unlock();
4747
Michael Wright2b3c3302018-03-02 17:19:13 +00004748 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004749 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004750 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751 : nullptr;
4752 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004753 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4754 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004755 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
4758 mLock.lock();
4759
4760 if (delay < 0) {
4761 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4762 } else if (!delay) {
4763 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4764 } else {
4765 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4766 entry->interceptKeyWakeupTime = now() + delay;
4767 }
4768 entry->release();
4769}
4770
chaviwfd6d3512019-03-25 13:23:49 -07004771void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4772 mLock.unlock();
4773 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4774 mLock.lock();
4775}
4776
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004777/**
4778 * Connection is responsive if it has no events in the waitQueue that are older than the
4779 * current time.
4780 */
4781static bool isConnectionResponsive(const Connection& connection) {
4782 const nsecs_t currentTime = now();
4783 for (const DispatchEntry* entry : connection.waitQueue) {
4784 if (entry->timeoutTime < currentTime) {
4785 return false;
4786 }
4787 }
4788 return true;
4789}
4790
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004793 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004795 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
4797 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004798 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004799 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004800 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004802 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004803 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004804 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004805 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4806 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004807 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004808 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004809
4810 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004811 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004812 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4813 restartEvent =
4814 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004815 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004816 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4817 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4818 handled);
4819 } else {
4820 restartEvent = false;
4821 }
4822
4823 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004824 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004825 // contents of the wait queue to have been drained, so we need to double-check
4826 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004827 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4828 if (dispatchEntryIt != connection->waitQueue.end()) {
4829 dispatchEntry = *dispatchEntryIt;
4830 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004831 mAnrTracker.erase(dispatchEntry->timeoutTime,
4832 connection->inputChannel->getConnectionToken());
4833 if (!connection->responsive) {
4834 connection->responsive = isConnectionResponsive(*connection);
4835 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004836 traceWaitQueueLength(connection);
4837 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004838 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004839 traceOutboundQueueLength(connection);
4840 } else {
4841 releaseDispatchEntry(dispatchEntry);
4842 }
4843 }
4844
4845 // Start the next dispatch cycle for this connection.
4846 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847}
4848
4849bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004850 DispatchEntry* dispatchEntry,
4851 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004852 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004853 if (!handled) {
4854 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004855 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004856 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004857 return false;
4858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004860 // Get the fallback key state.
4861 // Clear it out after dispatching the UP.
4862 int32_t originalKeyCode = keyEntry->keyCode;
4863 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4864 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4865 connection->inputState.removeFallbackKey(originalKeyCode);
4866 }
4867
4868 if (handled || !dispatchEntry->hasForegroundTarget()) {
4869 // If the application handles the original key for which we previously
4870 // generated a fallback or if the window is not a foreground window,
4871 // then cancel the associated fallback key, if any.
4872 if (fallbackKeyCode != -1) {
4873 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004875 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4877 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4878 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004880 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004881 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
4883 mLock.unlock();
4884
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004885 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004886 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887
4888 mLock.lock();
4889
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004890 // Cancel the fallback key.
4891 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004893 "application handled the original non-fallback key "
4894 "or is no longer a foreground target, "
4895 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 options.keyCode = fallbackKeyCode;
4897 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004899 connection->inputState.removeFallbackKey(originalKeyCode);
4900 }
4901 } else {
4902 // If the application did not handle a non-fallback key, first check
4903 // that we are in a good state to perform unhandled key event processing
4904 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004905 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004906 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004908 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004909 "since this is not an initial down. "
4910 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4911 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004913 return false;
4914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916 // Dispatch the unhandled key to the policy.
4917#if DEBUG_OUTBOUND_EVENT_DETAILS
4918 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004919 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4920 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004921#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004922 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004923
4924 mLock.unlock();
4925
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004926 bool fallback =
4927 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4928 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004929
4930 mLock.lock();
4931
4932 if (connection->status != Connection::STATUS_NORMAL) {
4933 connection->inputState.removeFallbackKey(originalKeyCode);
4934 return false;
4935 }
4936
4937 // Latch the fallback keycode for this key on an initial down.
4938 // The fallback keycode cannot change at any other point in the lifecycle.
4939 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004941 fallbackKeyCode = event.getKeyCode();
4942 } else {
4943 fallbackKeyCode = AKEYCODE_UNKNOWN;
4944 }
4945 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4946 }
4947
4948 ALOG_ASSERT(fallbackKeyCode != -1);
4949
4950 // Cancel the fallback key if the policy decides not to send it anymore.
4951 // We will continue to dispatch the key to the policy but we will no
4952 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004953 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4954 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004955#if DEBUG_OUTBOUND_EVENT_DETAILS
4956 if (fallback) {
4957 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004958 "as a fallback for %d, but on the DOWN it had requested "
4959 "to send %d instead. Fallback canceled.",
4960 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961 } else {
4962 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004963 "but on the DOWN it had requested to send %d. "
4964 "Fallback canceled.",
4965 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004966 }
4967#endif
4968
4969 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4970 "canceling fallback, policy no longer desires it");
4971 options.keyCode = fallbackKeyCode;
4972 synthesizeCancelationEventsForConnectionLocked(connection, options);
4973
4974 fallback = false;
4975 fallbackKeyCode = AKEYCODE_UNKNOWN;
4976 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004977 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004978 }
4979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980
4981#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982 {
4983 std::string msg;
4984 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4985 connection->inputState.getFallbackKeys();
4986 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004987 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004989 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004991 }
4992#endif
4993
4994 if (fallback) {
4995 // Restart the dispatch cycle using the fallback key.
4996 keyEntry->eventTime = event.getEventTime();
4997 keyEntry->deviceId = event.getDeviceId();
4998 keyEntry->source = event.getSource();
4999 keyEntry->displayId = event.getDisplayId();
5000 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5001 keyEntry->keyCode = fallbackKeyCode;
5002 keyEntry->scanCode = event.getScanCode();
5003 keyEntry->metaState = event.getMetaState();
5004 keyEntry->repeatCount = event.getRepeatCount();
5005 keyEntry->downTime = event.getDownTime();
5006 keyEntry->syntheticRepeat = false;
5007
5008#if DEBUG_OUTBOUND_EVENT_DETAILS
5009 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005010 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5011 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005012#endif
5013 return true; // restart the event
5014 } else {
5015#if DEBUG_OUTBOUND_EVENT_DETAILS
5016 ALOGD("Unhandled key event: No fallback key.");
5017#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005018
5019 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005020 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022 }
5023 return false;
5024}
5025
5026bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005027 DispatchEntry* dispatchEntry,
5028 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 return false;
5030}
5031
5032void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5033 mLock.unlock();
5034
5035 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5036
5037 mLock.lock();
5038}
5039
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005040KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5041 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005042 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08005043 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5044 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005045 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046}
5047
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07005048void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5049 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 // TODO Write some statistics about how long we spend waiting.
5051}
5052
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005053/**
5054 * Report the touch event latency to the statsd server.
5055 * Input events are reported for statistics if:
5056 * - This is a touchscreen event
5057 * - InputFilter is not enabled
5058 * - Event is not injected or synthesized
5059 *
5060 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5061 * from getting aggregated with the "old" data.
5062 */
5063void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5064 REQUIRES(mLock) {
5065 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5066 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5067 if (!reportForStatistics) {
5068 return;
5069 }
5070
5071 if (mTouchStatistics.shouldReport()) {
5072 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5073 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5074 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5075 mTouchStatistics.reset();
5076 }
5077 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5078 mTouchStatistics.addValue(latencyMicros);
5079}
5080
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081void InputDispatcher::traceInboundQueueLengthLocked() {
5082 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005083 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 }
5085}
5086
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005087void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088 if (ATRACE_ENABLED()) {
5089 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005090 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005091 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093}
5094
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005095void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 if (ATRACE_ENABLED()) {
5097 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005098 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005099 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101}
5102
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005103void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005104 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 dumpDispatchStateLocked(dump);
5108
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005109 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005111 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113}
5114
5115void InputDispatcher::monitor() {
5116 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005117 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005119 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120}
5121
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005122/**
5123 * Wake up the dispatcher and wait until it processes all events and commands.
5124 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5125 * this method can be safely called from any thread, as long as you've ensured that
5126 * the work you are interested in completing has already been queued.
5127 */
5128bool InputDispatcher::waitForIdle() {
5129 /**
5130 * Timeout should represent the longest possible time that a device might spend processing
5131 * events and commands.
5132 */
5133 constexpr std::chrono::duration TIMEOUT = 100ms;
5134 std::unique_lock lock(mLock);
5135 mLooper->wake();
5136 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5137 return result == std::cv_status::no_timeout;
5138}
5139
Garfield Tane84e6f92019-08-29 17:28:41 -07005140} // namespace android::inputdispatcher