blob: 0fa2332e40afcef1481bcd402ba5562a429cd589 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Michael Wrightd02c5b62014-02-10 15:10:22 -080092// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070098// Additional key latency in case a connection is still processing some motion events.
99// This will help with the case when a user touched a button that opens a new window,
100// and gives us the chance to dispatch the key to this new window.
101constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000104constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106static inline nsecs_t now() {
107 return systemTime(SYSTEM_TIME_MONOTONIC);
108}
109
110static inline const char* toString(bool value) {
111 return value ? "true" : "false";
112}
113
114static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700115 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
116 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117}
118
119static bool isValidKeyAction(int32_t action) {
120 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 case AKEY_EVENT_ACTION_DOWN:
122 case AKEY_EVENT_ACTION_UP:
123 return true;
124 default:
125 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 }
127}
128
129static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131 ALOGE("Key event has invalid action code 0x%x", action);
132 return false;
133 }
134 return true;
135}
136
Michael Wright7b159c92015-05-14 14:48:03 +0100137static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 case AMOTION_EVENT_ACTION_DOWN:
140 case AMOTION_EVENT_ACTION_UP:
141 case AMOTION_EVENT_ACTION_CANCEL:
142 case AMOTION_EVENT_ACTION_MOVE:
143 case AMOTION_EVENT_ACTION_OUTSIDE:
144 case AMOTION_EVENT_ACTION_HOVER_ENTER:
145 case AMOTION_EVENT_ACTION_HOVER_MOVE:
146 case AMOTION_EVENT_ACTION_HOVER_EXIT:
147 case AMOTION_EVENT_ACTION_SCROLL:
148 return true;
149 case AMOTION_EVENT_ACTION_POINTER_DOWN:
150 case AMOTION_EVENT_ACTION_POINTER_UP: {
151 int32_t index = getMotionEventActionPointerIndex(action);
152 return index >= 0 && index < pointerCount;
153 }
154 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
155 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
156 return actionButton != 0;
157 default:
158 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 }
160}
161
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500162static int64_t millis(std::chrono::nanoseconds t) {
163 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
164}
165
Michael Wright7b159c92015-05-14 14:48:03 +0100166static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 const PointerProperties* pointerProperties) {
168 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 ALOGE("Motion event has invalid action code 0x%x", action);
170 return false;
171 }
172 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000173 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 return false;
176 }
177 BitSet32 pointerIdBits;
178 for (size_t i = 0; i < pointerCount; i++) {
179 int32_t id = pointerProperties[i].id;
180 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
182 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 return false;
184 }
185 if (pointerIdBits.hasBit(id)) {
186 ALOGE("Motion event has duplicate pointer id %d", id);
187 return false;
188 }
189 pointerIdBits.markBit(id);
190 }
191 return true;
192}
193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800194static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800196 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 return;
198 }
199
200 bool first = true;
201 Region::const_iterator cur = region.begin();
202 Region::const_iterator const tail = region.end();
203 while (cur != tail) {
204 if (first) {
205 first = false;
206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800209 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 cur++;
211 }
212}
213
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700214/**
215 * Find the entry in std::unordered_map by key, and return it.
216 * If the entry is not found, return a default constructed entry.
217 *
218 * Useful when the entries are vectors, since an empty vector will be returned
219 * if the entry is not found.
220 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
221 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222template <typename K, typename V>
223static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700224 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800226}
227
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228/**
229 * Find the entry in std::unordered_map by value, and remove it.
230 * If more than one entry has the same value, then all matching
231 * key-value pairs will be removed.
232 *
233 * Return true if at least one value has been removed.
234 */
235template <typename K, typename V>
236static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
237 bool removed = false;
238 for (auto it = map.begin(); it != map.end();) {
239 if (it->second == value) {
240 it = map.erase(it);
241 removed = true;
242 } else {
243 it++;
244 }
245 }
246 return removed;
247}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
chaviwaf87b3e2019-10-01 16:59:28 -0700249static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
250 if (first == second) {
251 return true;
252 }
253
254 if (first == nullptr || second == nullptr) {
255 return false;
256 }
257
258 return first->getToken() == second->getToken();
259}
260
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800261static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
262 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
263}
264
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000265static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
266 EventEntry* eventEntry,
267 int32_t inputTargetFlags) {
268 if (inputTarget.useDefaultPointerInfo()) {
269 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
270 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
271 inputTargetFlags, pointerInfo.xOffset,
272 pointerInfo.yOffset, inputTarget.globalScaleFactor,
273 pointerInfo.windowXScale, pointerInfo.windowYScale);
274 }
275
276 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
277 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
278
279 PointerCoords pointerCoords[motionEntry.pointerCount];
280
281 // Use the first pointer information to normalize all other pointers. This could be any pointer
282 // as long as all other pointers are normalized to the same value and the final DispatchEntry
283 // uses the offset and scale for the normalized pointer.
284 const PointerInfo& firstPointerInfo =
285 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
286
287 // Iterate through all pointers in the event to normalize against the first.
288 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
289 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
290 uint32_t pointerId = uint32_t(pointerProperties.id);
291 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
292
293 // The scale factor is the ratio of the current pointers scale to the normalized scale.
294 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
295 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
296
297 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
298 // First apply the current pointers offset to set the window at 0,0
299 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
300 // Next scale the coordinates.
301 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
302 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
303 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
304 -firstPointerInfo.yOffset);
305 }
306
307 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800308 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000309 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
310 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
311 motionEntry.metaState, motionEntry.buttonState,
312 motionEntry.classification, motionEntry.edgeFlags,
313 motionEntry.xPrecision, motionEntry.yPrecision,
314 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
315 motionEntry.downTime, motionEntry.pointerCount,
316 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
317 0 /* yOffset */);
318
319 if (motionEntry.injectionState) {
320 combinedMotionEntry->injectionState = motionEntry.injectionState;
321 combinedMotionEntry->injectionState->refCount += 1;
322 }
323
324 std::unique_ptr<DispatchEntry> dispatchEntry =
325 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
326 inputTargetFlags, firstPointerInfo.xOffset,
327 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
328 firstPointerInfo.windowXScale,
329 firstPointerInfo.windowYScale);
330 combinedMotionEntry->release();
331 return dispatchEntry;
332}
333
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700334static void addGestureMonitors(const std::vector<Monitor>& monitors,
335 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
336 float yOffset = 0) {
337 if (monitors.empty()) {
338 return;
339 }
340 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
341 for (const Monitor& monitor : monitors) {
342 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
343 }
344}
345
Gang Wang342c9272020-01-13 13:15:04 -0500346static std::array<uint8_t, 128> getRandomKey() {
347 std::array<uint8_t, 128> key;
348 if (RAND_bytes(key.data(), key.size()) != 1) {
349 LOG_ALWAYS_FATAL("Can't generate HMAC key");
350 }
351 return key;
352}
353
354// --- HmacKeyManager ---
355
356HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
357
358std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
359 size_t size;
360 switch (event.type) {
361 case VerifiedInputEvent::Type::KEY: {
362 size = sizeof(VerifiedKeyEvent);
363 break;
364 }
365 case VerifiedInputEvent::Type::MOTION: {
366 size = sizeof(VerifiedMotionEvent);
367 break;
368 }
369 }
Gang Wang342c9272020-01-13 13:15:04 -0500370 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700371 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500372}
373
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700374std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500375 // SHA256 always generates 32-bytes result
376 std::array<uint8_t, 32> hash;
377 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700378 uint8_t* result =
379 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500380 if (result == nullptr) {
381 ALOGE("Could not sign the data using HMAC");
382 return INVALID_HMAC;
383 }
384
385 if (hashLen != hash.size()) {
386 ALOGE("HMAC-SHA256 has unexpected length");
387 return INVALID_HMAC;
388 }
389
390 return hash;
391}
392
Michael Wrightd02c5b62014-02-10 15:10:22 -0800393// --- InputDispatcher ---
394
Garfield Tan00f511d2019-06-12 16:55:40 -0700395InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
396 : mPolicy(policy),
397 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700398 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800399 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700400 mAppSwitchSawKeyDown(false),
401 mAppSwitchDueTime(LONG_LONG_MAX),
402 mNextUnblockedEvent(nullptr),
403 mDispatchEnabled(false),
404 mDispatchFrozen(false),
405 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800406 // mInTouchMode will be initialized by the WindowManager to the default device config.
407 // To avoid leaking stack in case that call never comes, and for tests,
408 // initialize it here anyways.
409 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700410 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800412 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
Yi Kong9b14ac62018-07-17 13:48:38 -0700414 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415
416 policy->getDispatcherConfiguration(&mConfig);
417}
418
419InputDispatcher::~InputDispatcher() {
420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
423 resetKeyRepeatLocked();
424 releasePendingEventLocked();
425 drainInboundQueueLocked();
426 }
427
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700428 while (!mConnectionsByFd.empty()) {
429 sp<Connection> connection = mConnectionsByFd.begin()->second;
430 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432}
433
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700435 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436 return ALREADY_EXISTS;
437 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700438 mThread = std::make_unique<InputThread>(
439 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
440 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441}
442
443status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 if (mThread && mThread->isCallingThread()) {
445 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446 return INVALID_OPERATION;
447 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700448 mThread.reset();
449 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700450}
451
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452void InputDispatcher::dispatchOnce() {
453 nsecs_t nextWakeupTime = LONG_LONG_MAX;
454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800455 std::scoped_lock _l(mLock);
456 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457
458 // Run a dispatch loop if there are no pending commands.
459 // The dispatch loop might enqueue commands to run afterwards.
460 if (!haveCommandsLocked()) {
461 dispatchOnceInnerLocked(&nextWakeupTime);
462 }
463
464 // Run all pending commands if there are any.
465 // If any commands were run then force the next poll to wake up immediately.
466 if (runCommandsLockedInterruptible()) {
467 nextWakeupTime = LONG_LONG_MIN;
468 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800469
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700470 // If we are still waiting for ack on some events,
471 // we might have to wake up earlier to check if an app is anr'ing.
472 const nsecs_t nextAnrCheck = processAnrsLocked();
473 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
474
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800475 // We are about to enter an infinitely long sleep, because we have no commands or
476 // pending or queued events
477 if (nextWakeupTime == LONG_LONG_MAX) {
478 mDispatcherEnteredIdle.notify_all();
479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480 } // release lock
481
482 // Wait for callback or timeout or wake. (make sure we round up, not down)
483 nsecs_t currentTime = now();
484 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
485 mLooper->pollOnce(timeoutMillis);
486}
487
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700488/**
489 * Check if any of the connections' wait queues have events that are too old.
490 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
491 * Return the time at which we should wake up next.
492 */
493nsecs_t InputDispatcher::processAnrsLocked() {
494 const nsecs_t currentTime = now();
495 nsecs_t nextAnrCheck = LONG_LONG_MAX;
496 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
497 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
498 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
499 onAnrLocked(mAwaitedFocusedApplication);
500 mAwaitedFocusedApplication.clear();
501 return LONG_LONG_MIN;
502 } else {
503 // Keep waiting
504 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
505 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
506 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
507 }
508 }
509
510 // Check if any connection ANRs are due
511 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
512 if (currentTime < nextAnrCheck) { // most likely scenario
513 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
514 }
515
516 // If we reached here, we have an unresponsive connection.
517 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
518 if (connection == nullptr) {
519 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
520 return nextAnrCheck;
521 }
522 connection->responsive = false;
523 // Stop waking up for this unresponsive connection
524 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
525 onAnrLocked(connection);
526 return LONG_LONG_MIN;
527}
528
529nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
530 sp<InputWindowHandle> window = getWindowHandleLocked(token);
531 if (window != nullptr) {
532 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
533 }
534 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
535}
536
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
538 nsecs_t currentTime = now();
539
Jeff Browndc5992e2014-04-11 01:27:26 -0700540 // Reset the key repeat timer whenever normal dispatch is suspended while the
541 // device is in a non-interactive state. This is to ensure that we abort a key
542 // repeat if the device is just coming out of sleep.
543 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 resetKeyRepeatLocked();
545 }
546
547 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
548 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100549 if (DEBUG_FOCUS) {
550 ALOGD("Dispatch frozen. Waiting some more.");
551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 return;
553 }
554
555 // Optimize latency of app switches.
556 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
557 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
558 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
559 if (mAppSwitchDueTime < *nextWakeupTime) {
560 *nextWakeupTime = mAppSwitchDueTime;
561 }
562
563 // Ready to start a new event.
564 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700565 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700566 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 if (isAppSwitchDue) {
568 // The inbound queue is empty so the app switch key we were waiting
569 // for will never arrive. Stop waiting for it.
570 resetPendingAppSwitchLocked(false);
571 isAppSwitchDue = false;
572 }
573
574 // Synthesize a key repeat if appropriate.
575 if (mKeyRepeatState.lastKeyEntry) {
576 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
577 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
578 } else {
579 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
580 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
581 }
582 }
583 }
584
585 // Nothing to do if there is no pending event.
586 if (!mPendingEvent) {
587 return;
588 }
589 } else {
590 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700591 mPendingEvent = mInboundQueue.front();
592 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 traceInboundQueueLengthLocked();
594 }
595
596 // Poke user activity for this event.
597 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
601
602 // Now we have an event to dispatch.
603 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700604 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700608 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700614 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 }
616
617 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700618 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 ConfigurationChangedEntry* typedEntry =
620 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
621 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700622 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 break;
624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700626 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700627 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
628 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700629 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 break;
631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100633 case EventEntry::Type::FOCUS: {
634 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
635 dispatchFocusLocked(currentTime, typedEntry);
636 done = true;
637 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
638 break;
639 }
640
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700641 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
643 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700644 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 resetPendingAppSwitchLocked(true);
646 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700647 } else if (dropReason == DropReason::NOT_DROPPED) {
648 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
650 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700651 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700652 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700654 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
655 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700656 }
657 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
658 break;
659 }
660
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700661 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700662 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
664 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700666 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
670 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700671 }
672 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
673 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676
677 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700679 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
Michael Wright3a981722015-06-10 15:26:13 +0100681 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
683 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686}
687
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700688/**
689 * Return true if the events preceding this incoming motion event should be dropped
690 * Return false otherwise (the default behaviour)
691 */
692bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700693 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700694 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700695
696 // Optimize case where the current application is unresponsive and the user
697 // decides to touch a window in a different application.
698 // If the application takes too long to catch up then we drop all events preceding
699 // the touch into the other window.
700 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700701 int32_t displayId = motionEntry.displayId;
702 int32_t x = static_cast<int32_t>(
703 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
704 int32_t y = static_cast<int32_t>(
705 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
706 sp<InputWindowHandle> touchedWindowHandle =
707 findTouchedWindowAtLocked(displayId, x, y, nullptr);
708 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700709 touchedWindowHandle->getApplicationToken() !=
710 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700711 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 ALOGI("Pruning input queue because user touched a different application while waiting "
713 "for %s",
714 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700715 return true;
716 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717
718 // Alternatively, maybe there's a gesture monitor that could handle this event
719 std::vector<TouchedMonitor> gestureMonitors =
720 findTouchedGestureMonitorsLocked(displayId, {});
721 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
722 sp<Connection> connection =
723 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000724 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725 // This monitor could take more input. Drop all events preceding this
726 // event, so that gesture monitor could get a chance to receive the stream
727 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
728 "responsive gesture monitor that may handle the event",
729 mAwaitedFocusedApplication->getName().c_str());
730 return true;
731 }
732 }
733 }
734
735 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
736 // yet been processed by some connections, the dispatcher will wait for these motion
737 // events to be processed before dispatching the key event. This is because these motion events
738 // may cause a new window to be launched, which the user might expect to receive focus.
739 // To prevent waiting forever for such events, just send the key to the currently focused window
740 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
741 ALOGD("Received a new pointer down event, stop waiting for events to process and "
742 "just send the pending key event to the focused window.");
743 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700744 }
745 return false;
746}
747
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700749 bool needWake = mInboundQueue.empty();
750 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 traceInboundQueueLengthLocked();
752
753 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700754 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 // Optimize app switch latency.
756 // If the application takes too long to catch up then we drop all events preceding
757 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700760 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700762 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700765 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700767 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 mAppSwitchSawKeyDown = false;
769 needWake = true;
770 }
771 }
772 }
773 break;
774 }
775
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700776 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700777 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
778 mNextUnblockedEvent = entry;
779 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100783 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700784 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
785 break;
786 }
787 case EventEntry::Type::CONFIGURATION_CHANGED:
788 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700789 // nothing to do
790 break;
791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 return needWake;
795}
796
797void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
798 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700799 mRecentQueue.push_back(entry);
800 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
801 mRecentQueue.front()->release();
802 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804}
805
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700807 int32_t y, TouchState* touchState,
808 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700810 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
811 LOG_ALWAYS_FATAL(
812 "Must provide a valid touch state if adding portal windows or outside targets");
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800815 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
816 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 const InputWindowInfo* windowInfo = windowHandle->getInfo();
818 if (windowInfo->displayId == displayId) {
819 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820
821 if (windowInfo->visible) {
822 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700823 bool isTouchModal = (flags &
824 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
825 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800827 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 if (portalToDisplayId != ADISPLAY_ID_NONE &&
829 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 if (addPortalWindows) {
831 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700832 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800833 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 // Found window.
838 return windowHandle;
839 }
840 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841
842 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700843 touchState->addOrUpdateWindow(windowHandle,
844 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
845 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
849 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700850 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Garfield Tane84e6f92019-08-29 17:28:41 -0700853std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700854 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000855 std::vector<TouchedMonitor> touchedMonitors;
856
857 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
858 addGestureMonitors(monitors, touchedMonitors);
859 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
860 const InputWindowInfo* windowInfo = portalWindow->getInfo();
861 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
863 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000864 }
865 return touchedMonitors;
866}
867
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700868void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 const char* reason;
870 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 reason = "inbound event was dropped because the policy consumed it";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::DISABLED:
878 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 ALOGI("Dropped event because input dispatch is disabled.");
880 }
881 reason = "inbound event was dropped because input dispatch is disabled";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because of pending overdue app switch.");
885 reason = "inbound event was dropped because of pending overdue app switch";
886 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 ALOGI("Dropped event because the current application is not responding and the user "
889 "has started interacting with a different application.");
890 reason = "inbound event was dropped because the current application is not responding "
891 "and the user has started interacting with a different application";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 ALOGI("Dropped event because it is stale.");
895 reason = "inbound event was dropped because it is stale";
896 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::NOT_DROPPED: {
898 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
906 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700909 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
911 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
913 synthesizeCancelationEventsForAllConnectionsLocked(options);
914 } else {
915 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
916 synthesizeCancelationEventsForAllConnectionsLocked(options);
917 }
918 break;
919 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100920 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::CONFIGURATION_CHANGED:
922 case EventEntry::Type::DEVICE_RESET: {
923 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927}
928
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800929static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
931 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932}
933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
935 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
936 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
937 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938}
939
940bool InputDispatcher::isAppSwitchPendingLocked() {
941 return mAppSwitchDueTime != LONG_LONG_MAX;
942}
943
944void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
945 mAppSwitchDueTime = LONG_LONG_MAX;
946
947#if DEBUG_APP_SWITCH
948 if (handled) {
949 ALOGD("App switch has arrived.");
950 } else {
951 ALOGD("App switch was abandoned.");
952 }
953#endif
954}
955
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700961 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 return false;
963 }
964
965 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700966 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700969 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
971 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return true;
974}
975
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
977 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
980void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 while (!mInboundQueue.empty()) {
982 EventEntry* entry = mInboundQueue.front();
983 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 releaseInboundEventLocked(entry);
985 }
986 traceInboundQueueLengthLocked();
987}
988
989void InputDispatcher::releasePendingEventLocked() {
990 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700992 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994}
995
996void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
997 InjectionState* injectionState = entry->injectionState;
998 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
999#if DEBUG_DISPATCH_CYCLE
1000 ALOGD("Injected inbound event was dropped.");
1001#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001002 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007 addRecentEventLocked(entry);
1008 entry->release();
1009}
1010
1011void InputDispatcher::resetKeyRepeatLocked() {
1012 if (mKeyRepeatState.lastKeyEntry) {
1013 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001014 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016}
1017
Garfield Tane84e6f92019-08-29 17:28:41 -07001018KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1020
1021 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001022 uint32_t policyFlags = entry->policyFlags &
1023 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 if (entry->refCount == 1) {
1025 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001026 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 entry->eventTime = currentTime;
1028 entry->policyFlags = policyFlags;
1029 entry->repeatCount += 1;
1030 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001032 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001033 entry->displayId, policyFlags, entry->action, entry->flags,
1034 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
1037 mKeyRepeatState.lastKeyEntry = newEntry;
1038 entry->release();
1039
1040 entry = newEntry;
1041 }
1042 entry->syntheticRepeat = true;
1043
1044 // Increment reference count since we keep a reference to the event in
1045 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1046 entry->refCount += 1;
1047
1048 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1049 return entry;
1050}
1051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1053 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001055 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056#endif
1057
1058 // Reset key repeating in case a keyboard device was added or removed or something.
1059 resetKeyRepeatLocked();
1060
1061 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001062 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1063 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001065 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 return true;
1067}
1068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001071 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073#endif
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 options.deviceId = entry->deviceId;
1077 synthesizeCancelationEventsForAllConnectionsLocked(options);
1078 return true;
1079}
1080
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001081void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001082 if (mPendingEvent != nullptr) {
1083 // Move the pending event to the front of the queue. This will give the chance
1084 // for the pending event to get dispatched to the newly focused window
1085 mInboundQueue.push_front(mPendingEvent);
1086 mPendingEvent = nullptr;
1087 }
1088
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001090 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091
1092 // This event should go to the front of the queue, but behind all other focus events
1093 // Find the last focus event, and insert right after it
1094 std::deque<EventEntry*>::reverse_iterator it =
1095 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1096 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1097
1098 // Maintain the order of focus events. Insert the entry after all other focus events.
1099 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100}
1101
1102void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1103 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1104 if (channel == nullptr) {
1105 return; // Window has gone away
1106 }
1107 InputTarget target;
1108 target.inputChannel = channel;
1109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1110 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 dispatchEventLocked(currentTime, entry, {target});
1113}
1114
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 if (!entry->dispatchInProgress) {
1119 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1120 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1121 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1122 if (mKeyRepeatState.lastKeyEntry &&
1123 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 // We have seen two identical key downs in a row which indicates that the device
1125 // driver is automatically generating key repeats itself. We take note of the
1126 // repeat here, but we disable our own next key repeat timer since it is clear that
1127 // we will not need to synthesize key repeats ourselves.
1128 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1131 } else {
1132 // Not a repeat. Save key down state in case we do see a repeat later.
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1135 }
1136 mKeyRepeatState.lastKeyEntry = entry;
1137 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 resetKeyRepeatLocked();
1140 }
1141
1142 if (entry->repeatCount == 1) {
1143 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1144 } else {
1145 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1146 }
1147
1148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Handle case where the policy asked us to try again later last time.
1154 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1155 if (currentTime < entry->interceptKeyWakeupTime) {
1156 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1157 *nextWakeupTime = entry->interceptKeyWakeupTime;
1158 }
1159 return false; // wait until next wakeup
1160 }
1161 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1162 entry->interceptKeyWakeupTime = 0;
1163 }
1164
1165 // Give the policy a chance to intercept the key.
1166 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1167 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001168 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001169 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001170 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 entry->refCount += 1;
1178 return false; // wait for the command to run
1179 } else {
1180 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1181 }
1182 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001183 if (*dropReason == DropReason::NOT_DROPPED) {
1184 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186 }
1187
1188 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001193 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195 }
1196
1197 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001198 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1202 return false;
1203 }
1204
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001205 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1207 return true;
1208 }
1209
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001210 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
1213 // Dispatch the key.
1214 dispatchEventLocked(currentTime, entry, inputTargets);
1215 return true;
1216}
1217
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001220 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1222 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001223 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1224 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1225 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#endif
1227}
1228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1230 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001231 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 entry->dispatchInProgress = true;
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return true;
1245 }
1246
1247 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1248
1249 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 bool conflictingPointerActions = false;
1253 int32_t injectionResult;
1254 if (isPointerEvent) {
1255 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 } else {
1260 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1265 return false;
1266 }
1267
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001268 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001269 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1270 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1271 return true;
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001274 CancelationOptions::Mode mode(isPointerEvent
1275 ? CancelationOptions::CANCEL_POINTER_EVENTS
1276 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1277 CancelationOptions options(mode, "input event injection failed");
1278 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001285 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001286 std::unordered_map<int32_t, TouchState>::iterator it =
1287 mTouchStatesByDisplay.find(entry->displayId);
1288 if (it != mTouchStatesByDisplay.end()) {
1289 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001291 // The event has gone through these portal windows, so we add monitoring targets of
1292 // the corresponding displays as well.
1293 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001295 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001297 }
1298 }
1299 }
1300 }
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // Dispatch the motion.
1303 if (conflictingPointerActions) {
1304 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 synthesizeCancelationEventsForAllConnectionsLocked(options);
1307 }
1308 dispatchEventLocked(currentTime, entry, inputTargets);
1309 return true;
1310}
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001314 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 ", policyFlags=0x%x, "
1316 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1317 "metaState=0x%x, buttonState=0x%x,"
1318 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1320 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1321 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 "x=%f, y=%f, pressure=%f, size=%f, "
1326 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1327 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001328 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339#endif
1340}
1341
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001342void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1343 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001344 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345#if DEBUG_DISPATCH_CYCLE
1346 ALOGD("dispatchEventToCurrentInputTargets");
1347#endif
1348
1349 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001353 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001354 sp<Connection> connection =
1355 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001356 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001357 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001359 if (DEBUG_FOCUS) {
1360 ALOGD("Dropping event delivery to target with channel '%s' because it "
1361 "is no longer registered with the input dispatcher.",
1362 inputTarget.inputChannel->getName().c_str());
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 }
1366}
1367
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001368void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1369 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1370 // If the policy decides to close the app, we will get a channel removal event via
1371 // unregisterInputChannel, and will clean up the connection that way. We are already not
1372 // sending new pointers to the connection when it blocked, but focused events will continue to
1373 // pile up.
1374 ALOGW("Canceling events for %s because it is unresponsive",
1375 connection->inputChannel->getName().c_str());
1376 if (connection->status == Connection::STATUS_NORMAL) {
1377 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1378 "application not responding");
1379 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381}
1382
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001383void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389 mNoFocusedWindowTimeoutTime = std::nullopt;
1390 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001421bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1422 const char* focusedWindowName) {
1423 if (mAnrTracker.empty()) {
1424 // already processed all events that we waited for
1425 mKeyIsWaitingForEventsTimeout = std::nullopt;
1426 return false;
1427 }
1428
1429 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1430 // Start the timer
1431 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1432 "focus to change",
1433 focusedWindowName);
1434 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1435 return true;
1436 }
1437
1438 // We still have pending events, and already started the timer
1439 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1440 return true; // Still waiting
1441 }
1442
1443 // Waited too long, and some connection still hasn't processed all motions
1444 // Just send the key to the focused window
1445 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1446 focusedWindowName);
1447 mKeyIsWaitingForEventsTimeout = std::nullopt;
1448 return false;
1449}
1450
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001452 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 std::vector<InputTarget>& inputTargets,
1454 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001455 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456
Tiger Huang721e26f2018-07-24 22:26:19 +08001457 int32_t displayId = getTargetDisplayId(entry);
1458 sp<InputWindowHandle> focusedWindowHandle =
1459 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1460 sp<InputApplicationHandle> focusedApplicationHandle =
1461 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1462
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 // If there is no currently focused window and no focused application
1464 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1466 ALOGI("Dropping %s event because there is no focused window or focused application in "
1467 "display %" PRId32 ".",
1468 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001469 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
1471
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001472 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1473 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1474 // start interacting with another application via touch (app switch). This code can be removed
1475 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1476 // an app is expected to have a focused window.
1477 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1478 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1479 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001480 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1481 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1482 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001483 mAwaitedFocusedApplication = focusedApplicationHandle;
1484 ALOGW("Waiting because no window has focus but %s may eventually add a "
1485 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001486 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001487 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1488 return INPUT_EVENT_INJECTION_PENDING;
1489 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1490 // Already raised ANR. Drop the event
1491 ALOGE("Dropping %s event because there is no focused window",
1492 EventEntry::typeToString(entry.type));
1493 return INPUT_EVENT_INJECTION_FAILED;
1494 } else {
1495 // Still waiting for the focused window
1496 return INPUT_EVENT_INJECTION_PENDING;
1497 }
1498 }
1499
1500 // we have a valid, non-null focused window
1501 resetNoFocusedWindowTimeoutLocked();
1502
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001505 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
1507
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001508 if (focusedWindowHandle->getInfo()->paused) {
1509 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1510 return INPUT_EVENT_INJECTION_PENDING;
1511 }
1512
1513 // If the event is a key event, then we must wait for all previous events to
1514 // complete before delivering it because previous events may have the
1515 // side-effect of transferring focus to a different window and we want to
1516 // ensure that the following keys are sent to the new window.
1517 //
1518 // Suppose the user touches a button in a window then immediately presses "A".
1519 // If the button causes a pop-up window to appear then we want to ensure that
1520 // the "A" key is delivered to the new pop-up window. This is because users
1521 // often anticipate pending UI changes when typing on a keyboard.
1522 // To obtain this behavior, we must serialize key events with respect to all
1523 // prior input events.
1524 if (entry.type == EventEntry::Type::KEY) {
1525 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1526 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1527 return INPUT_EVENT_INJECTION_PENDING;
1528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530
1531 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001532 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001533 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1534 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001537 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538}
1539
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001540/**
1541 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1542 * that are currently unresponsive.
1543 */
1544std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1545 const std::vector<TouchedMonitor>& monitors) const {
1546 std::vector<TouchedMonitor> responsiveMonitors;
1547 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1548 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1549 sp<Connection> connection = getConnectionLocked(
1550 monitor.monitor.inputChannel->getConnectionToken());
1551 if (connection == nullptr) {
1552 ALOGE("Could not find connection for monitor %s",
1553 monitor.monitor.inputChannel->getName().c_str());
1554 return false;
1555 }
1556 if (!connection->responsive) {
1557 ALOGW("Unresponsive monitor %s will not get the new gesture",
1558 connection->inputChannel->getName().c_str());
1559 return false;
1560 }
1561 return true;
1562 });
1563 return responsiveMonitors;
1564}
1565
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 std::vector<InputTarget>& inputTargets,
1569 nsecs_t* nextWakeupTime,
1570 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 enum InjectionPermission {
1573 INJECTION_PERMISSION_UNKNOWN,
1574 INJECTION_PERMISSION_GRANTED,
1575 INJECTION_PERMISSION_DENIED
1576 };
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // For security reasons, we defer updating the touch state until we are sure that
1579 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 int32_t displayId = entry.displayId;
1581 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1583
1584 // Update the touch state as needed based on the properties of the touch event.
1585 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1586 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1587 sp<InputWindowHandle> newHoverWindowHandle;
1588
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001589 // Copy current touch state into tempTouchState.
1590 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1591 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001592 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001593 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001594 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1595 mTouchStatesByDisplay.find(displayId);
1596 if (oldStateIt != mTouchStatesByDisplay.end()) {
1597 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001598 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001599 }
1600
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001601 bool isSplit = tempTouchState.split;
1602 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1603 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1604 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001605 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1606 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1607 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1608 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1609 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 bool wrongDevice = false;
1612 if (newGesture) {
1613 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001614 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001615 ALOGI("Dropping event because a pointer for a different device is already down "
1616 "in display %" PRId32,
1617 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001618 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1620 switchedDevice = false;
1621 wrongDevice = true;
1622 goto Failed;
1623 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001624 tempTouchState.reset();
1625 tempTouchState.down = down;
1626 tempTouchState.deviceId = entry.deviceId;
1627 tempTouchState.source = entry.source;
1628 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001630 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001631 ALOGI("Dropping move event because a pointer for a different device is already active "
1632 "in display %" PRId32,
1633 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001634 // TODO: test multiple simultaneous input streams.
1635 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1636 switchedDevice = false;
1637 wrongDevice = true;
1638 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 }
1640
1641 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1642 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1643
Garfield Tan00f511d2019-06-12 16:55:40 -07001644 int32_t x;
1645 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001647 // Always dispatch mouse events to cursor position.
1648 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 x = int32_t(entry.xCursorPosition);
1650 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001651 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001652 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1653 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001654 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001655 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001657 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1658 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001659
1660 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001661 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001662 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 if (newTouchedWindowHandle != nullptr &&
1666 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001667 // New window supports splitting, but we should never split mouse events.
1668 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 } else if (isSplit) {
1670 // New window does not support splitting but we have already split events.
1671 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001672 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 }
1674
1675 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001676 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001678 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001679 }
1680
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001681 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1682 ALOGI("Not sending touch event to %s because it is paused",
1683 newTouchedWindowHandle->getName().c_str());
1684 newTouchedWindowHandle = nullptr;
1685 }
1686
1687 if (newTouchedWindowHandle != nullptr) {
1688 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1689 if (connection == nullptr) {
1690 ALOGI("Could not find connection for %s",
1691 newTouchedWindowHandle->getName().c_str());
1692 newTouchedWindowHandle = nullptr;
1693 } else if (!connection->responsive) {
1694 // don't send the new touch to an unresponsive window
1695 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1696 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1697 newTouchedWindowHandle = nullptr;
1698 }
1699 }
1700
1701 // Also don't send the new touch event to unresponsive gesture monitors
1702 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1703
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1705 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001706 "(%d, %d) in display %" PRId32 ".",
1707 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001708 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1709 goto Failed;
1710 }
1711
1712 if (newTouchedWindowHandle != nullptr) {
1713 // Set target flags.
1714 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1715 if (isSplit) {
1716 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1719 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1720 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1721 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1722 }
1723
1724 // Update hover state.
1725 if (isHoverAction) {
1726 newHoverWindowHandle = newTouchedWindowHandle;
1727 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1728 newHoverWindowHandle = mLastHoverWindowHandle;
1729 }
1730
1731 // Update the temporary touch state.
1732 BitSet32 pointerIds;
1733 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 pointerIds.markBit(pointerId);
1736 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001737 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001740 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 } else {
1742 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1743
1744 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001745 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001746 if (DEBUG_FOCUS) {
1747 ALOGD("Dropping event because the pointer is not down or we previously "
1748 "dropped the pointer down event in display %" PRId32,
1749 displayId);
1750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1752 goto Failed;
1753 }
1754
1755 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001757 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001758 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1759 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
1761 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001762 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001764 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1766 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001767 if (DEBUG_FOCUS) {
1768 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1769 oldTouchedWindowHandle->getName().c_str(),
1770 newTouchedWindowHandle->getName().c_str(), displayId);
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001773 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1774 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1775 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 // Make a slippery entrance into the new window.
1778 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1779 isSplit = true;
1780 }
1781
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 int32_t targetFlags =
1783 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 if (isSplit) {
1785 targetFlags |= InputTarget::FLAG_SPLIT;
1786 }
1787 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1788 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1789 }
1790
1791 BitSet32 pointerIds;
1792 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001795 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
1797 }
1798 }
1799
1800 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1801 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001802 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803#if DEBUG_HOVER
1804 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001807 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1808 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
1810
1811 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001812 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813#if DEBUG_HOVER
1814 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001815 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001817 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1818 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1819 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
1821 }
1822
1823 // Check permission to inject into all touched foreground windows and ensure there
1824 // is at least one touched foreground window.
1825 {
1826 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001827 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1829 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1832 injectionPermission = INJECTION_PERMISSION_DENIED;
1833 goto Failed;
1834 }
1835 }
1836 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001837 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001838 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001839 ALOGI("Dropping event because there is no touched foreground window in display "
1840 "%" PRId32 " or gesture monitor to receive it.",
1841 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1843 goto Failed;
1844 }
1845
1846 // Permission granted to injection into all touched foreground windows.
1847 injectionPermission = INJECTION_PERMISSION_GRANTED;
1848 }
1849
1850 // Check whether windows listening for outside touches are owned by the same UID. If it is
1851 // set the policy flag that we will not reveal coordinate information to this window.
1852 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1853 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001854 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001855 if (foregroundWindowHandle) {
1856 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001858 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1859 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1860 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1862 InputTarget::FLAG_ZERO_COORDS,
1863 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866 }
1867 }
1868 }
1869
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 // If this is the first pointer going down and the touched window has a wallpaper
1871 // then also add the touched wallpaper windows so they are locked in for the duration
1872 // of the touch gesture.
1873 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1874 // engine only supports touch events. We would need to add a mechanism similar
1875 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1876 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1877 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001878 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001879 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001880 const std::vector<sp<InputWindowHandle>> windowHandles =
1881 getWindowHandlesLocked(displayId);
1882 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884 if (info->displayId == displayId &&
1885 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001886 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 .addOrUpdateWindow(windowHandle,
1888 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1889 InputTarget::
1890 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1891 InputTarget::FLAG_DISPATCH_AS_IS,
1892 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 }
1894 }
1895 }
1896 }
1897
1898 // Success! Output targets.
1899 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1900
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001901 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001903 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001906 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001907 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001909 }
1910
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 // Drop the outside or hover touch windows since we will not care about them
1912 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001913 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914
1915Failed:
1916 // Check injection permission once and for all.
1917 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001918 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 injectionPermission = INJECTION_PERMISSION_GRANTED;
1920 } else {
1921 injectionPermission = INJECTION_PERMISSION_DENIED;
1922 }
1923 }
1924
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001925 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1926 return injectionResult;
1927 }
1928
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001930 if (!wrongDevice) {
1931 if (switchedDevice) {
1932 if (DEBUG_FOCUS) {
1933 ALOGD("Conflicting pointer actions: Switched to a different device.");
1934 }
1935 *outConflictingPointerActions = true;
1936 }
1937
1938 if (isHoverAction) {
1939 // Started hovering, therefore no longer down.
1940 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001941 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001942 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1943 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 *outConflictingPointerActions = true;
1946 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 tempTouchState.reset();
1948 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1949 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1950 tempTouchState.deviceId = entry.deviceId;
1951 tempTouchState.source = entry.source;
1952 tempTouchState.displayId = displayId;
1953 }
1954 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1955 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1956 // All pointers up or canceled.
1957 tempTouchState.reset();
1958 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1959 // First pointer went down.
1960 if (oldState && oldState->down) {
1961 if (DEBUG_FOCUS) {
1962 ALOGD("Conflicting pointer actions: Down received while already down.");
1963 }
1964 *outConflictingPointerActions = true;
1965 }
1966 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1967 // One pointer went up.
1968 if (isSplit) {
1969 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1970 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001972 for (size_t i = 0; i < tempTouchState.windows.size();) {
1973 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1974 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1975 touchedWindow.pointerIds.clearBit(pointerId);
1976 if (touchedWindow.pointerIds.isEmpty()) {
1977 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1978 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001981 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001983 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001985
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 // Save changes unless the action was scroll in which case the temporary touch
1987 // state was only valid for this one action.
1988 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1989 if (tempTouchState.displayId >= 0) {
1990 mTouchStatesByDisplay[displayId] = tempTouchState;
1991 } else {
1992 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001996 // Update hover state.
1997 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
1999
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 return injectionResult;
2001}
2002
2003void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002004 int32_t targetFlags, BitSet32 pointerIds,
2005 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002006 std::vector<InputTarget>::iterator it =
2007 std::find_if(inputTargets.begin(), inputTargets.end(),
2008 [&windowHandle](const InputTarget& inputTarget) {
2009 return inputTarget.inputChannel->getConnectionToken() ==
2010 windowHandle->getToken();
2011 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002012
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002013 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002014
2015 if (it == inputTargets.end()) {
2016 InputTarget inputTarget;
2017 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2018 if (inputChannel == nullptr) {
2019 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2020 return;
2021 }
2022 inputTarget.inputChannel = inputChannel;
2023 inputTarget.flags = targetFlags;
2024 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2025 inputTargets.push_back(inputTarget);
2026 it = inputTargets.end() - 1;
2027 }
2028
2029 ALOG_ASSERT(it->flags == targetFlags);
2030 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2031
2032 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2033 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034}
2035
Michael Wright3dd60e22019-03-27 22:06:44 +00002036void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002037 int32_t displayId, float xOffset,
2038 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002039 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2040 mGlobalMonitorsByDisplay.find(displayId);
2041
2042 if (it != mGlobalMonitorsByDisplay.end()) {
2043 const std::vector<Monitor>& monitors = it->second;
2044 for (const Monitor& monitor : monitors) {
2045 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048}
2049
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2051 float yOffset,
2052 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 InputTarget target;
2054 target.inputChannel = monitor.inputChannel;
2055 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002056 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002057 inputTargets.push_back(target);
2058}
2059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002061 const InjectionState* injectionState) {
2062 if (injectionState &&
2063 (windowHandle == nullptr ||
2064 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2065 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002066 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 "owned by uid %d",
2069 injectionState->injectorPid, injectionState->injectorUid,
2070 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 } else {
2072 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002073 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 }
2075 return false;
2076 }
2077 return true;
2078}
2079
Robert Carrc9bf1d32020-04-13 17:21:08 -07002080/**
2081 * Indicate whether one window handle should be considered as obscuring
2082 * another window handle. We only check a few preconditions. Actually
2083 * checking the bounds is left to the caller.
2084 */
2085static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2086 const sp<InputWindowHandle>& otherHandle) {
2087 // Compare by token so cloned layers aren't counted
2088 if (haveSameToken(windowHandle, otherHandle)) {
2089 return false;
2090 }
2091 auto info = windowHandle->getInfo();
2092 auto otherInfo = otherHandle->getInfo();
2093 if (!otherInfo->visible) {
2094 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002095 } else if (info->ownerPid == otherInfo->ownerPid) {
2096 // If ownerPid is the same we don't generate occlusion events as there
2097 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002098 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002099 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002100 return false;
2101 } else if (otherInfo->displayId != info->displayId) {
2102 return false;
2103 }
2104 return true;
2105}
2106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2108 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002110 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2111 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002112 if (windowHandle == otherHandle) {
2113 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002116 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002117 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 return true;
2119 }
2120 }
2121 return false;
2122}
2123
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002124bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2125 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002126 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002127 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002128 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002129 if (windowHandle == otherHandle) {
2130 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002131 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002132 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002133 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002134 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002135 return true;
2136 }
2137 }
2138 return false;
2139}
2140
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002141std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 const sp<InputApplicationHandle>& applicationHandle,
2143 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002144 if (applicationHandle != nullptr) {
2145 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002146 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 } else {
2148 return applicationHandle->getName();
2149 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002150 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002151 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002153 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155}
2156
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002157void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002158 if (eventEntry.type == EventEntry::Type::FOCUS) {
2159 // Focus events are passed to apps, but do not represent user activity.
2160 return;
2161 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002162 int32_t displayId = getTargetDisplayId(eventEntry);
2163 sp<InputWindowHandle> focusedWindowHandle =
2164 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2165 if (focusedWindowHandle != nullptr) {
2166 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2168#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002169 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170#endif
2171 return;
2172 }
2173 }
2174
2175 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002176 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002177 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002178 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2179 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 return;
2181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002183 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 eventType = USER_ACTIVITY_EVENT_TOUCH;
2185 }
2186 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002188 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2190 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 return;
2192 }
2193 eventType = USER_ACTIVITY_EVENT_BUTTON;
2194 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002196 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002197 case EventEntry::Type::CONFIGURATION_CHANGED:
2198 case EventEntry::Type::DEVICE_RESET: {
2199 LOG_ALWAYS_FATAL("%s events are not user activity",
2200 EventEntry::typeToString(eventEntry.type));
2201 break;
2202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
2204
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002205 std::unique_ptr<CommandEntry> commandEntry =
2206 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002207 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002209 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210}
2211
2212void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 const sp<Connection>& connection,
2214 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002215 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002216 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002218 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002219 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002220 ATRACE_NAME(message.c_str());
2221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222#if DEBUG_DISPATCH_CYCLE
2223 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002224 "globalScaleFactor=%f, pointerIds=0x%x %s",
2225 connection->getInputChannelName().c_str(), inputTarget.flags,
2226 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2227 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#endif
2229
2230 // Skip this event if the connection status is not normal.
2231 // We don't want to enqueue additional outbound events if the connection is broken.
2232 if (connection->status != Connection::STATUS_NORMAL) {
2233#if DEBUG_DISPATCH_CYCLE
2234 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002235 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236#endif
2237 return;
2238 }
2239
2240 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002241 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2242 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2243 "Entry type %s should not have FLAG_SPLIT",
2244 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002246 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002249 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 if (!splitMotionEntry) {
2251 return; // split event was dropped
2252 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002253 if (DEBUG_FOCUS) {
2254 ALOGD("channel '%s' ~ Split motion event.",
2255 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002256 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002257 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 splitMotionEntry->release();
2260 return;
2261 }
2262 }
2263
2264 // Not splitting. Enqueue dispatch entries for the event as is.
2265 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2266}
2267
2268void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 const sp<Connection>& connection,
2270 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002271 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002274 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002275 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002276 ATRACE_NAME(message.c_str());
2277 }
2278
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002279 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280
2281 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294
2295 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002296 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 startDispatchCycleLocked(currentTime, connection);
2298 }
2299}
2300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2302 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002303 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2307 connection->getInputChannelName().c_str(),
2308 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 ATRACE_NAME(message.c_str());
2310 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002311 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (!(inputTargetFlags & dispatchMode)) {
2313 return;
2314 }
2315 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2316
2317 // This is a new event.
2318 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002319 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002320 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002322 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2323 // different EventEntry than what was passed in.
2324 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002327 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002329 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002330 dispatchEntry->resolvedAction = keyEntry.action;
2331 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2334 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2337 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 return; // skip the inconsistent event
2340 }
2341 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002344 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002345 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002346 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2347 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2348 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2349 static_cast<int32_t>(IdGenerator::Source::OTHER);
2350 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002351 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2355 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2357 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2361 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002362 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002363 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002364 }
2365 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002366 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2367 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2370 "event",
2371 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002376 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2378 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2379 }
2380 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2381 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2385 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2388 "event",
2389 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002391 return; // skip the inconsistent event
2392 }
2393
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002394 dispatchEntry->resolvedEventId =
2395 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2396 ? mIdGenerator.nextId()
2397 : motionEntry.id;
2398 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2399 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2400 ") to MotionEvent(id=0x%" PRIx32 ").",
2401 motionEntry.id, dispatchEntry->resolvedEventId);
2402 ATRACE_NAME(message.c_str());
2403 }
2404
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002405 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002406 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002407
2408 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002410 case EventEntry::Type::FOCUS: {
2411 break;
2412 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002413 case EventEntry::Type::CONFIGURATION_CHANGED:
2414 case EventEntry::Type::DEVICE_RESET: {
2415 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002416 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002417 break;
2418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
2420
2421 // Remember that we are waiting for this dispatch to complete.
2422 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002423 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425
2426 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002427 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002428 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002429}
2430
chaviwfd6d3512019-03-25 13:23:49 -07002431void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002433 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002434 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2435 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002436 return;
2437 }
2438
2439 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2440 if (inputWindowHandle == nullptr) {
2441 return;
2442 }
2443
chaviw8c9cf542019-03-25 13:02:48 -07002444 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002445 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002446
2447 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2448
2449 if (!hasFocusChanged) {
2450 return;
2451 }
2452
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002453 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2454 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002455 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002456 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457}
2458
2459void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002461 if (ATRACE_ENABLED()) {
2462 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002464 ATRACE_NAME(message.c_str());
2465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468#endif
2469
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002470 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2471 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002473 const nsecs_t timeout =
2474 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2475 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476
2477 // Publish the event.
2478 status_t status;
2479 EventEntry* eventEntry = dispatchEntry->eventEntry;
2480 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002481 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002482 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2483 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002486 status =
2487 connection->inputPublisher
2488 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2489 keyEntry->deviceId, keyEntry->source,
2490 keyEntry->displayId, std::move(hmac),
2491 dispatchEntry->resolvedAction,
2492 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2493 keyEntry->scanCode, keyEntry->metaState,
2494 keyEntry->repeatCount, keyEntry->downTime,
2495 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
2498
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002499 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 PointerCoords scaledCoords[MAX_POINTERS];
2503 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2504
chaviw82357092020-01-28 13:13:06 -08002505 // Set the X and Y offset and X and Y scale depending on the input source.
2506 float xOffset = 0.0f, yOffset = 0.0f;
2507 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2509 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2510 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002511 xScale = dispatchEntry->windowXScale;
2512 yScale = dispatchEntry->windowYScale;
2513 xOffset = dispatchEntry->xOffset * xScale;
2514 yOffset = dispatchEntry->yOffset * yScale;
2515 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2517 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002518 // Don't apply window scale here since we don't want scale to affect raw
2519 // coordinates. The scale will be sent back to the client and applied
2520 // later when requesting relative coordinates.
2521 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2522 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 }
2524 usingCoords = scaledCoords;
2525 }
2526 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 // We don't want the dispatch target to know.
2528 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2529 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2530 scaledCoords[i].clear();
2531 }
2532 usingCoords = scaledCoords;
2533 }
2534 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002535
2536 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537
2538 // Publish the motion event.
2539 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002540 .publishMotionEvent(dispatchEntry->seq,
2541 dispatchEntry->resolvedEventId,
2542 motionEntry->deviceId, motionEntry->source,
2543 motionEntry->displayId, std::move(hmac),
2544 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002545 motionEntry->actionButton,
2546 dispatchEntry->resolvedFlags,
2547 motionEntry->edgeFlags, motionEntry->metaState,
2548 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002549 motionEntry->classification, xScale, yScale,
2550 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 motionEntry->yPrecision,
2552 motionEntry->xCursorPosition,
2553 motionEntry->yCursorPosition,
2554 motionEntry->downTime, motionEntry->eventTime,
2555 motionEntry->pointerCount,
2556 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002557 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 break;
2559 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002560 case EventEntry::Type::FOCUS: {
2561 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2562 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002563 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002564 focusEntry->hasFocus,
2565 mInTouchMode);
2566 break;
2567 }
2568
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002569 case EventEntry::Type::CONFIGURATION_CHANGED:
2570 case EventEntry::Type::DEVICE_RESET: {
2571 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2572 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 }
2576
2577 // Check the result.
2578 if (status) {
2579 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002580 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 "This is unexpected because the wait queue is empty, so the pipe "
2583 "should be empty and we shouldn't have any problems writing an "
2584 "event to it, status=%d",
2585 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2587 } else {
2588 // Pipe is full and we are waiting for the app to finish process some events
2589 // before sending more events to it.
2590#if DEBUG_DISPATCH_CYCLE
2591 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 "waiting for the application to catch up",
2593 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 }
2596 } else {
2597 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 "status=%d",
2599 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2601 }
2602 return;
2603 }
2604
2605 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002606 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2607 connection->outboundQueue.end(),
2608 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002609 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002610 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002611 if (connection->responsive) {
2612 mAnrTracker.insert(dispatchEntry->timeoutTime,
2613 connection->inputChannel->getConnectionToken());
2614 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002615 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 }
2617}
2618
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002619const std::array<uint8_t, 32> InputDispatcher::getSignature(
2620 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2621 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2622 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2623 // Only sign events up and down events as the purely move events
2624 // are tied to their up/down counterparts so signing would be redundant.
2625 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2626 verifiedEvent.actionMasked = actionMasked;
2627 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2628 return mHmacKeyManager.sign(verifiedEvent);
2629 }
2630 return INVALID_HMAC;
2631}
2632
2633const std::array<uint8_t, 32> InputDispatcher::getSignature(
2634 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2635 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2636 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2637 verifiedEvent.action = dispatchEntry.resolvedAction;
2638 return mHmacKeyManager.sign(verifiedEvent);
2639}
2640
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 const sp<Connection>& connection, uint32_t seq,
2643 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644#if DEBUG_DISPATCH_CYCLE
2645 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647#endif
2648
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002649 if (connection->status == Connection::STATUS_BROKEN ||
2650 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 return;
2652 }
2653
2654 // Notify other system components and prepare to start the next dispatch cycle.
2655 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2656}
2657
2658void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 const sp<Connection>& connection,
2660 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661#if DEBUG_DISPATCH_CYCLE
2662 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664#endif
2665
2666 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002667 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002668 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002669 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002670 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671
2672 // The connection appears to be unrecoverably broken.
2673 // Ignore already broken or zombie connections.
2674 if (connection->status == Connection::STATUS_NORMAL) {
2675 connection->status = Connection::STATUS_BROKEN;
2676
2677 if (notify) {
2678 // Notify other system components.
2679 onDispatchCycleBrokenLocked(currentTime, connection);
2680 }
2681 }
2682}
2683
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002684void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2685 while (!queue.empty()) {
2686 DispatchEntry* dispatchEntry = queue.front();
2687 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002688 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 }
2690}
2691
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002692void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002694 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
2696 delete dispatchEntry;
2697}
2698
2699int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2700 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2701
2702 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002703 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002705 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 "fd=%d, events=0x%x",
2708 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 return 0; // remove the callback
2710 }
2711
2712 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002713 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2715 if (!(events & ALOOPER_EVENT_INPUT)) {
2716 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 "events=0x%x",
2718 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 return 1;
2720 }
2721
2722 nsecs_t currentTime = now();
2723 bool gotOne = false;
2724 status_t status;
2725 for (;;) {
2726 uint32_t seq;
2727 bool handled;
2728 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2729 if (status) {
2730 break;
2731 }
2732 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2733 gotOne = true;
2734 }
2735 if (gotOne) {
2736 d->runCommandsLockedInterruptible();
2737 if (status == WOULD_BLOCK) {
2738 return 1;
2739 }
2740 }
2741
2742 notify = status != DEAD_OBJECT || !connection->monitor;
2743 if (notify) {
2744 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 }
2747 } else {
2748 // Monitor channels are never explicitly unregistered.
2749 // We do it automatically when the remote endpoint is closed so don't warn
2750 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002751 const bool stillHaveWindowHandle =
2752 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2753 nullptr;
2754 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 if (notify) {
2756 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002757 "events=0x%x",
2758 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 }
2760 }
2761
2762 // Unregister the channel.
2763 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2764 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766}
2767
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002770 for (const auto& pair : mConnectionsByFd) {
2771 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 }
2773}
2774
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002776 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002777 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2778 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2779}
2780
2781void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2782 const CancelationOptions& options,
2783 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2784 for (const auto& it : monitorsByDisplay) {
2785 const std::vector<Monitor>& monitors = it.second;
2786 for (const Monitor& monitor : monitors) {
2787 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002788 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002789 }
2790}
2791
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2793 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002794 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002795 if (connection == nullptr) {
2796 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002798
2799 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800}
2801
2802void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2803 const sp<Connection>& connection, const CancelationOptions& options) {
2804 if (connection->status == Connection::STATUS_BROKEN) {
2805 return;
2806 }
2807
2808 nsecs_t currentTime = now();
2809
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002810 std::vector<EventEntry*> cancelationEvents =
2811 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002813 if (cancelationEvents.empty()) {
2814 return;
2815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002817 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2818 "with reality: %s, mode=%d.",
2819 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2820 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002822
2823 InputTarget target;
2824 sp<InputWindowHandle> windowHandle =
2825 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2826 if (windowHandle != nullptr) {
2827 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2828 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2829 windowInfo->windowXScale, windowInfo->windowYScale);
2830 target.globalScaleFactor = windowInfo->globalScaleFactor;
2831 }
2832 target.inputChannel = connection->inputChannel;
2833 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2834
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002835 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2836 EventEntry* cancelationEventEntry = cancelationEvents[i];
2837 switch (cancelationEventEntry->type) {
2838 case EventEntry::Type::KEY: {
2839 logOutboundKeyDetails("cancel - ",
2840 static_cast<const KeyEntry&>(*cancelationEventEntry));
2841 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002843 case EventEntry::Type::MOTION: {
2844 logOutboundMotionDetails("cancel - ",
2845 static_cast<const MotionEntry&>(*cancelationEventEntry));
2846 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002848 case EventEntry::Type::FOCUS: {
2849 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2850 break;
2851 }
2852 case EventEntry::Type::CONFIGURATION_CHANGED:
2853 case EventEntry::Type::DEVICE_RESET: {
2854 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2855 EventEntry::typeToString(cancelationEventEntry->type));
2856 break;
2857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
2859
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002860 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2861 target, InputTarget::FLAG_DISPATCH_AS_IS);
2862
2863 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002865
2866 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867}
2868
Svet Ganov5d3bc372020-01-26 23:11:07 -08002869void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2870 const sp<Connection>& connection) {
2871 if (connection->status == Connection::STATUS_BROKEN) {
2872 return;
2873 }
2874
2875 nsecs_t currentTime = now();
2876
2877 std::vector<EventEntry*> downEvents =
2878 connection->inputState.synthesizePointerDownEvents(currentTime);
2879
2880 if (downEvents.empty()) {
2881 return;
2882 }
2883
2884#if DEBUG_OUTBOUND_EVENT_DETAILS
2885 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2886 connection->getInputChannelName().c_str(), downEvents.size());
2887#endif
2888
2889 InputTarget target;
2890 sp<InputWindowHandle> windowHandle =
2891 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2892 if (windowHandle != nullptr) {
2893 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2894 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2895 windowInfo->windowXScale, windowInfo->windowYScale);
2896 target.globalScaleFactor = windowInfo->globalScaleFactor;
2897 }
2898 target.inputChannel = connection->inputChannel;
2899 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2900
2901 for (EventEntry* downEventEntry : downEvents) {
2902 switch (downEventEntry->type) {
2903 case EventEntry::Type::MOTION: {
2904 logOutboundMotionDetails("down - ",
2905 static_cast<const MotionEntry&>(*downEventEntry));
2906 break;
2907 }
2908
2909 case EventEntry::Type::KEY:
2910 case EventEntry::Type::FOCUS:
2911 case EventEntry::Type::CONFIGURATION_CHANGED:
2912 case EventEntry::Type::DEVICE_RESET: {
2913 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2914 EventEntry::typeToString(downEventEntry->type));
2915 break;
2916 }
2917 }
2918
2919 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2920 target, InputTarget::FLAG_DISPATCH_AS_IS);
2921
2922 downEventEntry->release();
2923 }
2924
2925 startDispatchCycleLocked(currentTime, connection);
2926}
2927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002928MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002929 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 ALOG_ASSERT(pointerIds.value != 0);
2931
2932 uint32_t splitPointerIndexMap[MAX_POINTERS];
2933 PointerProperties splitPointerProperties[MAX_POINTERS];
2934 PointerCoords splitPointerCoords[MAX_POINTERS];
2935
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002936 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 uint32_t splitPointerCount = 0;
2938
2939 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002942 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 uint32_t pointerId = uint32_t(pointerProperties.id);
2944 if (pointerIds.hasBit(pointerId)) {
2945 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2946 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2947 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 splitPointerCount += 1;
2950 }
2951 }
2952
2953 if (splitPointerCount != pointerIds.count()) {
2954 // This is bad. We are missing some of the pointers that we expected to deliver.
2955 // Most likely this indicates that we received an ACTION_MOVE events that has
2956 // different pointer ids than we expected based on the previous ACTION_DOWN
2957 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2958 // in this way.
2959 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 "we expected there to be %d pointers. This probably means we received "
2961 "a broken sequence of pointer ids from the input device.",
2962 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002963 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 }
2965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2969 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2971 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002972 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 uint32_t pointerId = uint32_t(pointerProperties.id);
2974 if (pointerIds.hasBit(pointerId)) {
2975 if (pointerIds.count() == 1) {
2976 // The first/last pointer went down/up.
2977 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 ? AMOTION_EVENT_ACTION_DOWN
2979 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 } else {
2981 // A secondary pointer went down/up.
2982 uint32_t splitPointerIndex = 0;
2983 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2984 splitPointerIndex += 1;
2985 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 action = maskedAction |
2987 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989 } else {
2990 // An unrelated pointer changed.
2991 action = AMOTION_EVENT_ACTION_MOVE;
2992 }
2993 }
2994
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002995 int32_t newId = mIdGenerator.nextId();
2996 if (ATRACE_ENABLED()) {
2997 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2998 ") to MotionEvent(id=0x%" PRIx32 ").",
2999 originalMotionEntry.id, newId);
3000 ATRACE_NAME(message.c_str());
3001 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003002 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003003 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3004 originalMotionEntry.source, originalMotionEntry.displayId,
3005 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 originalMotionEntry.actionButton, originalMotionEntry.flags,
3007 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3008 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3009 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3010 originalMotionEntry.xCursorPosition,
3011 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003012 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003014 if (originalMotionEntry.injectionState) {
3015 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016 splitMotionEntry->injectionState->refCount += 1;
3017 }
3018
3019 return splitMotionEntry;
3020}
3021
3022void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3023#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003024 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025#endif
3026
3027 bool needWake;
3028 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003029 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030
Prabir Pradhan42611e02018-11-27 14:04:02 -08003031 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003032 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 needWake = enqueueInboundEventLocked(newEntry);
3034 } // release lock
3035
3036 if (needWake) {
3037 mLooper->wake();
3038 }
3039}
3040
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003041/**
3042 * If one of the meta shortcuts is detected, process them here:
3043 * Meta + Backspace -> generate BACK
3044 * Meta + Enter -> generate HOME
3045 * This will potentially overwrite keyCode and metaState.
3046 */
3047void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003049 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3050 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3051 if (keyCode == AKEYCODE_DEL) {
3052 newKeyCode = AKEYCODE_BACK;
3053 } else if (keyCode == AKEYCODE_ENTER) {
3054 newKeyCode = AKEYCODE_HOME;
3055 }
3056 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003057 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003058 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003059 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003060 keyCode = newKeyCode;
3061 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3062 }
3063 } else if (action == AKEY_EVENT_ACTION_UP) {
3064 // In order to maintain a consistent stream of up and down events, check to see if the key
3065 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3066 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003067 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003068 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003069 auto replacementIt = mReplacedKeys.find(replacement);
3070 if (replacementIt != mReplacedKeys.end()) {
3071 keyCode = replacementIt->second;
3072 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003073 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3074 }
3075 }
3076}
3077
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3079#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3081 "policyFlags=0x%x, action=0x%x, "
3082 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3083 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3084 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3085 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#endif
3087 if (!validateKeyEvent(args->action)) {
3088 return;
3089 }
3090
3091 uint32_t policyFlags = args->policyFlags;
3092 int32_t flags = args->flags;
3093 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003094 // InputDispatcher tracks and generates key repeats on behalf of
3095 // whatever notifies it, so repeatCount should always be set to 0
3096 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3098 policyFlags |= POLICY_FLAG_VIRTUAL;
3099 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 if (policyFlags & POLICY_FLAG_FUNCTION) {
3102 metaState |= AMETA_FUNCTION_ON;
3103 }
3104
3105 policyFlags |= POLICY_FLAG_TRUSTED;
3106
Michael Wright78f24442014-08-06 15:55:28 -07003107 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003108 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003109
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003111 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003112 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3113 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
Michael Wright2b3c3302018-03-02 17:19:13 +00003115 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003117 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3118 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 bool needWake;
3123 { // acquire lock
3124 mLock.lock();
3125
3126 if (shouldSendKeyToInputFilterLocked(args)) {
3127 mLock.unlock();
3128
3129 policyFlags |= POLICY_FLAG_FILTERED;
3130 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3131 return; // event was consumed by the filter
3132 }
3133
3134 mLock.lock();
3135 }
3136
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003138 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 args->displayId, policyFlags, args->action, flags, keyCode,
3140 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
3142 needWake = enqueueInboundEventLocked(newEntry);
3143 mLock.unlock();
3144 } // release lock
3145
3146 if (needWake) {
3147 mLooper->wake();
3148 }
3149}
3150
3151bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3152 return mInputFilterEnabled;
3153}
3154
3155void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3156#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003157 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3158 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003159 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3160 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003161 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003162 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3163 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3164 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3165 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 for (uint32_t i = 0; i < args->pointerCount; i++) {
3167 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 "x=%f, y=%f, pressure=%f, size=%f, "
3169 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3170 "orientation=%f",
3171 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3177 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3178 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3179 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3180 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3184 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 return;
3186 }
3187
3188 uint32_t policyFlags = args->policyFlags;
3189 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003190
3191 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003192 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003193 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3194 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
3198 bool needWake;
3199 { // acquire lock
3200 mLock.lock();
3201
3202 if (shouldSendMotionToInputFilterLocked(args)) {
3203 mLock.unlock();
3204
3205 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003206 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3207 args->action, args->actionButton, args->flags, args->edgeFlags,
3208 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3209 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3210 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3211 args->downTime, args->eventTime, args->pointerCount,
3212 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
3214 policyFlags |= POLICY_FLAG_FILTERED;
3215 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3216 return; // event was consumed by the filter
3217 }
3218
3219 mLock.lock();
3220 }
3221
3222 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003223 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003224 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003225 args->displayId, policyFlags, args->action, args->actionButton,
3226 args->flags, args->metaState, args->buttonState,
3227 args->classification, args->edgeFlags, args->xPrecision,
3228 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3229 args->downTime, args->pointerCount, args->pointerProperties,
3230 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231
3232 needWake = enqueueInboundEventLocked(newEntry);
3233 mLock.unlock();
3234 } // release lock
3235
3236 if (needWake) {
3237 mLooper->wake();
3238 }
3239}
3240
3241bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003242 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243}
3244
3245void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3246#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003247 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 "switchMask=0x%08x",
3249 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250#endif
3251
3252 uint32_t policyFlags = args->policyFlags;
3253 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255}
3256
3257void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3258#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3260 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261#endif
3262
3263 bool needWake;
3264 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003265 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266
Prabir Pradhan42611e02018-11-27 14:04:02 -08003267 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003268 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 needWake = enqueueInboundEventLocked(newEntry);
3270 } // release lock
3271
3272 if (needWake) {
3273 mLooper->wake();
3274 }
3275}
3276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3278 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003279 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#if DEBUG_INBOUND_EVENT_DETAILS
3281 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003282 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3283 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284#endif
3285
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003286 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
3288 policyFlags |= POLICY_FLAG_INJECTED;
3289 if (hasInjectionPermission(injectorPid, injectorUid)) {
3290 policyFlags |= POLICY_FLAG_TRUSTED;
3291 }
3292
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003293 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003296 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3297 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 if (!validateKeyEvent(action)) {
3299 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003302 int32_t flags = incomingKey.getFlags();
3303 int32_t keyCode = incomingKey.getKeyCode();
3304 int32_t metaState = incomingKey.getMetaState();
3305 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003307 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003308 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003309 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3310 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3311 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3314 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003315 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316
3317 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3318 android::base::Timer t;
3319 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3320 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3321 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3322 std::to_string(t.duration().count()).c_str());
3323 }
3324 }
3325
3326 mLock.lock();
3327 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003328 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3329 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003330 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3331 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003332 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 injectedEntries.push(injectedEntry);
3334 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
3336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 case AINPUT_EVENT_TYPE_MOTION: {
3338 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3339 int32_t action = motionEvent->getAction();
3340 size_t pointerCount = motionEvent->getPointerCount();
3341 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3342 int32_t actionButton = motionEvent->getActionButton();
3343 int32_t displayId = motionEvent->getDisplayId();
3344 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3345 return INPUT_EVENT_INJECTION_FAILED;
3346 }
3347
3348 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3349 nsecs_t eventTime = motionEvent->getEventTime();
3350 android::base::Timer t;
3351 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3352 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3353 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3354 std::to_string(t.duration().count()).c_str());
3355 }
3356 }
3357
3358 mLock.lock();
3359 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3360 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3361 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003362 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3363 motionEvent->getSource(), motionEvent->getDisplayId(),
3364 policyFlags, action, actionButton, motionEvent->getFlags(),
3365 motionEvent->getMetaState(), motionEvent->getButtonState(),
3366 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3367 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003368 motionEvent->getRawXCursorPosition(),
3369 motionEvent->getRawYCursorPosition(),
3370 motionEvent->getDownTime(), uint32_t(pointerCount),
3371 pointerProperties, samplePointerCoords,
3372 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 injectedEntries.push(injectedEntry);
3374 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3375 sampleEventTimes += 1;
3376 samplePointerCoords += pointerCount;
3377 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003378 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003379 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380 motionEvent->getDisplayId(), policyFlags, action,
3381 actionButton, motionEvent->getFlags(),
3382 motionEvent->getMetaState(), motionEvent->getButtonState(),
3383 motionEvent->getClassification(),
3384 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3385 motionEvent->getYPrecision(),
3386 motionEvent->getRawXCursorPosition(),
3387 motionEvent->getRawYCursorPosition(),
3388 motionEvent->getDownTime(), uint32_t(pointerCount),
3389 pointerProperties, samplePointerCoords,
3390 motionEvent->getXOffset(), motionEvent->getYOffset());
3391 injectedEntries.push(nextInjectedEntry);
3392 }
3393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003397 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
3401 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3402 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3403 injectionState->injectionIsAsync = true;
3404 }
3405
3406 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003407 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
3409 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003410 while (!injectedEntries.empty()) {
3411 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3412 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414
3415 mLock.unlock();
3416
3417 if (needWake) {
3418 mLooper->wake();
3419 }
3420
3421 int32_t injectionResult;
3422 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003423 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
3425 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3426 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3427 } else {
3428 for (;;) {
3429 injectionResult = injectionState->injectionResult;
3430 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3431 break;
3432 }
3433
3434 nsecs_t remainingTimeout = endTime - now();
3435 if (remainingTimeout <= 0) {
3436#if DEBUG_INJECTION
3437 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439#endif
3440 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3441 break;
3442 }
3443
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003444 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 }
3446
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3448 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 while (injectionState->pendingForegroundDispatches != 0) {
3450#if DEBUG_INJECTION
3451 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003452 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453#endif
3454 nsecs_t remainingTimeout = endTime - now();
3455 if (remainingTimeout <= 0) {
3456#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3458 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3461 break;
3462 }
3463
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003464 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 }
3466 }
3467 }
3468
3469 injectionState->release();
3470 } // release lock
3471
3472#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003473 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003474 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475#endif
3476
3477 return injectionResult;
3478}
3479
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003480std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003481 std::array<uint8_t, 32> calculatedHmac;
3482 std::unique_ptr<VerifiedInputEvent> result;
3483 switch (event.getType()) {
3484 case AINPUT_EVENT_TYPE_KEY: {
3485 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3486 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3487 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3488 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3489 break;
3490 }
3491 case AINPUT_EVENT_TYPE_MOTION: {
3492 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3493 VerifiedMotionEvent verifiedMotionEvent =
3494 verifiedMotionEventFromMotionEvent(motionEvent);
3495 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3496 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3497 break;
3498 }
3499 default: {
3500 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3501 return nullptr;
3502 }
3503 }
3504 if (calculatedHmac == INVALID_HMAC) {
3505 return nullptr;
3506 }
3507 if (calculatedHmac != event.getHmac()) {
3508 return nullptr;
3509 }
3510 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003511}
3512
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514 return injectorUid == 0 ||
3515 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516}
3517
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003518void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 InjectionState* injectionState = entry->injectionState;
3520 if (injectionState) {
3521#if DEBUG_INJECTION
3522 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 "injectorPid=%d, injectorUid=%d",
3524 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525#endif
3526
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 // Log the outcome since the injector did not wait for the injection result.
3529 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530 case INPUT_EVENT_INJECTION_SUCCEEDED:
3531 ALOGV("Asynchronous input event injection succeeded.");
3532 break;
3533 case INPUT_EVENT_INJECTION_FAILED:
3534 ALOGW("Asynchronous input event injection failed.");
3535 break;
3536 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3537 ALOGW("Asynchronous input event injection permission denied.");
3538 break;
3539 case INPUT_EVENT_INJECTION_TIMED_OUT:
3540 ALOGW("Asynchronous input event injection timed out.");
3541 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 }
3544
3545 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003546 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 }
3548}
3549
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003550void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 InjectionState* injectionState = entry->injectionState;
3552 if (injectionState) {
3553 injectionState->pendingForegroundDispatches += 1;
3554 }
3555}
3556
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003557void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 InjectionState* injectionState = entry->injectionState;
3559 if (injectionState) {
3560 injectionState->pendingForegroundDispatches -= 1;
3561
3562 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003563 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 }
3565 }
3566}
3567
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003568std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3569 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003570 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003571}
3572
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003574 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003575 if (windowHandleToken == nullptr) {
3576 return nullptr;
3577 }
3578
Arthur Hungb92218b2018-08-14 12:00:21 +08003579 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003580 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3581 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003582 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003583 return windowHandle;
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 }
3586 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003587 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588}
3589
Mady Mellor017bcd12020-06-23 19:12:00 +00003590bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3591 for (auto& it : mWindowHandlesByDisplay) {
3592 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3593 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003594 if (handle->getId() == windowHandle->getId() &&
3595 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003596 if (windowHandle->getInfo()->displayId != it.first) {
3597 ALOGE("Found window %s in display %" PRId32
3598 ", but it should belong to display %" PRId32,
3599 windowHandle->getName().c_str(), it.first,
3600 windowHandle->getInfo()->displayId);
3601 }
3602 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605 }
3606 return false;
3607}
3608
Robert Carr5c8a0262018-10-03 16:30:44 -07003609sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3610 size_t count = mInputChannelsByToken.count(token);
3611 if (count == 0) {
3612 return nullptr;
3613 }
3614 return mInputChannelsByToken.at(token);
3615}
3616
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003617void InputDispatcher::updateWindowHandlesForDisplayLocked(
3618 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3619 if (inputWindowHandles.empty()) {
3620 // Remove all handles on a display if there are no windows left.
3621 mWindowHandlesByDisplay.erase(displayId);
3622 return;
3623 }
3624
3625 // Since we compare the pointer of input window handles across window updates, we need
3626 // to make sure the handle object for the same window stays unchanged across updates.
3627 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003628 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003629 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003630 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003631 }
3632
3633 std::vector<sp<InputWindowHandle>> newHandles;
3634 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3635 if (!handle->updateInfo()) {
3636 // handle no longer valid
3637 continue;
3638 }
3639
3640 const InputWindowInfo* info = handle->getInfo();
3641 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3642 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3643 const bool noInputChannel =
3644 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3645 const bool canReceiveInput =
3646 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3647 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3648 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003649 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003650 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003651 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003652 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003653 }
3654
3655 if (info->displayId != displayId) {
3656 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3657 handle->getName().c_str(), displayId, info->displayId);
3658 continue;
3659 }
3660
Robert Carredd13602020-04-13 17:24:34 -07003661 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3662 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003663 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003664 oldHandle->updateFrom(handle);
3665 newHandles.push_back(oldHandle);
3666 } else {
3667 newHandles.push_back(handle);
3668 }
3669 }
3670
3671 // Insert or replace
3672 mWindowHandlesByDisplay[displayId] = newHandles;
3673}
3674
Arthur Hung72d8dc32020-03-28 00:48:39 +00003675void InputDispatcher::setInputWindows(
3676 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3677 { // acquire lock
3678 std::scoped_lock _l(mLock);
3679 for (auto const& i : handlesPerDisplay) {
3680 setInputWindowsLocked(i.second, i.first);
3681 }
3682 }
3683 // Wake up poll loop since it may need to make new input dispatching choices.
3684 mLooper->wake();
3685}
3686
Arthur Hungb92218b2018-08-14 12:00:21 +08003687/**
3688 * Called from InputManagerService, update window handle list by displayId that can receive input.
3689 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3690 * If set an empty list, remove all handles from the specific display.
3691 * For focused handle, check if need to change and send a cancel event to previous one.
3692 * For removed handle, check if need to send a cancel event if already in touch.
3693 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003694void InputDispatcher::setInputWindowsLocked(
3695 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003696 if (DEBUG_FOCUS) {
3697 std::string windowList;
3698 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3699 windowList += iwh->getName() + " ";
3700 }
3701 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703
Arthur Hung72d8dc32020-03-28 00:48:39 +00003704 // Copy old handles for release if they are no longer present.
3705 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
Arthur Hung72d8dc32020-03-28 00:48:39 +00003707 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003708
Arthur Hung72d8dc32020-03-28 00:48:39 +00003709 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3710 bool foundHoveredWindow = false;
3711 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3712 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3713 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3714 windowHandle->getInfo()->visible) {
3715 newFocusedWindowHandle = windowHandle;
3716 }
3717 if (windowHandle == mLastHoverWindowHandle) {
3718 foundHoveredWindow = true;
3719 }
3720 }
3721
3722 if (!foundHoveredWindow) {
3723 mLastHoverWindowHandle = nullptr;
3724 }
3725
3726 sp<InputWindowHandle> oldFocusedWindowHandle =
3727 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3728
3729 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3730 if (oldFocusedWindowHandle != nullptr) {
3731 if (DEBUG_FOCUS) {
3732 ALOGD("Focus left window: %s in display %" PRId32,
3733 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003734 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 sp<InputChannel> focusedInputChannel =
3736 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3737 if (focusedInputChannel != nullptr) {
3738 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3739 "focus left window");
3740 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3741 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003742 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743 mFocusedWindowHandlesByDisplay.erase(displayId);
3744 }
3745 if (newFocusedWindowHandle != nullptr) {
3746 if (DEBUG_FOCUS) {
3747 ALOGD("Focus entered window: %s in display %" PRId32,
3748 newFocusedWindowHandle->getName().c_str(), displayId);
3749 }
3750 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3751 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 }
3753
Arthur Hung72d8dc32020-03-28 00:48:39 +00003754 if (mFocusedDisplayId == displayId) {
3755 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003759 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3760 mTouchStatesByDisplay.find(displayId);
3761 if (stateIt != mTouchStatesByDisplay.end()) {
3762 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003763 for (size_t i = 0; i < state.windows.size();) {
3764 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003765 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003766 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003767 ALOGD("Touched window was removed: %s in display %" PRId32,
3768 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003769 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003770 sp<InputChannel> touchedInputChannel =
3771 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3772 if (touchedInputChannel != nullptr) {
3773 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3774 "touched window was removed");
3775 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003777 state.windows.erase(state.windows.begin() + i);
3778 } else {
3779 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 }
3781 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003782 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003783
Arthur Hung72d8dc32020-03-28 00:48:39 +00003784 // Release information for windows that are no longer present.
3785 // This ensures that unused input channels are released promptly.
3786 // Otherwise, they might stick around until the window handle is destroyed
3787 // which might not happen until the next GC.
3788 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003789 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790 if (DEBUG_FOCUS) {
3791 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003792 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003793 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003794 }
chaviw291d88a2019-02-14 10:33:58 -08003795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796}
3797
3798void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003799 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003800 if (DEBUG_FOCUS) {
3801 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3802 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003805 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
Tiger Huang721e26f2018-07-24 22:26:19 +08003807 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3808 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003809
3810 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3811 inputApplicationHandle != oldFocusedApplicationHandle) {
3812 resetNoFocusedWindowTimeoutLocked();
3813 }
3814
Yi Kong9b14ac62018-07-17 13:48:38 -07003815 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003816 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003817 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003819 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003820 oldFocusedApplicationHandle.clear();
3821 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 } // release lock
3824
3825 // Wake up poll loop since it may need to make new input dispatching choices.
3826 mLooper->wake();
3827}
3828
Tiger Huang721e26f2018-07-24 22:26:19 +08003829/**
3830 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3831 * the display not specified.
3832 *
3833 * We track any unreleased events for each window. If a window loses the ability to receive the
3834 * released event, we will send a cancel event to it. So when the focused display is changed, we
3835 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3836 * display. The display-specified events won't be affected.
3837 */
3838void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003839 if (DEBUG_FOCUS) {
3840 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3841 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003842 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003843 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003844
3845 if (mFocusedDisplayId != displayId) {
3846 sp<InputWindowHandle> oldFocusedWindowHandle =
3847 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3848 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003849 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003851 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003852 CancelationOptions
3853 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3854 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003855 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003856 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3857 }
3858 }
3859 mFocusedDisplayId = displayId;
3860
3861 // Sanity check
3862 sp<InputWindowHandle> newFocusedWindowHandle =
3863 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003864 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003865
Tiger Huang721e26f2018-07-24 22:26:19 +08003866 if (newFocusedWindowHandle == nullptr) {
3867 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3868 if (!mFocusedWindowHandlesByDisplay.empty()) {
3869 ALOGE("But another display has a focused window:");
3870 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003871 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003872 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003874 }
3875 }
3876 }
3877 }
3878
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003879 if (DEBUG_FOCUS) {
3880 logDispatchStateLocked();
3881 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003882 } // release lock
3883
3884 // Wake up poll loop since it may need to make new input dispatching choices.
3885 mLooper->wake();
3886}
3887
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003889 if (DEBUG_FOCUS) {
3890 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
3893 bool changed;
3894 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003895 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
3897 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3898 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003899 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901
3902 if (mDispatchEnabled && !enabled) {
3903 resetAndDropEverythingLocked("dispatcher is being disabled");
3904 }
3905
3906 mDispatchEnabled = enabled;
3907 mDispatchFrozen = frozen;
3908 changed = true;
3909 } else {
3910 changed = false;
3911 }
3912
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003913 if (DEBUG_FOCUS) {
3914 logDispatchStateLocked();
3915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 } // release lock
3917
3918 if (changed) {
3919 // Wake up poll loop since it may need to make new input dispatching choices.
3920 mLooper->wake();
3921 }
3922}
3923
3924void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003925 if (DEBUG_FOCUS) {
3926 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
3929 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003930 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
3932 if (mInputFilterEnabled == enabled) {
3933 return;
3934 }
3935
3936 mInputFilterEnabled = enabled;
3937 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3938 } // release lock
3939
3940 // Wake up poll loop since there might be work to do to drop everything.
3941 mLooper->wake();
3942}
3943
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003944void InputDispatcher::setInTouchMode(bool inTouchMode) {
3945 std::scoped_lock lock(mLock);
3946 mInTouchMode = inTouchMode;
3947}
3948
chaviwfbe5d9c2018-12-26 12:23:37 -08003949bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3950 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003951 if (DEBUG_FOCUS) {
3952 ALOGD("Trivial transfer to same window.");
3953 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003954 return true;
3955 }
3956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003958 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
chaviwfbe5d9c2018-12-26 12:23:37 -08003960 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3961 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003962 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003963 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 return false;
3965 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003966 if (DEBUG_FOCUS) {
3967 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3968 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003971 if (DEBUG_FOCUS) {
3972 ALOGD("Cannot transfer focus because windows are on different displays.");
3973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 return false;
3975 }
3976
3977 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003978 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3979 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003980 for (size_t i = 0; i < state.windows.size(); i++) {
3981 const TouchedWindow& touchedWindow = state.windows[i];
3982 if (touchedWindow.windowHandle == fromWindowHandle) {
3983 int32_t oldTargetFlags = touchedWindow.targetFlags;
3984 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003986 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 int32_t newTargetFlags = oldTargetFlags &
3989 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3990 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003991 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Jeff Brownf086ddb2014-02-11 14:28:48 -08003993 found = true;
3994 goto Found;
3995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003998 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004000 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004001 if (DEBUG_FOCUS) {
4002 ALOGD("Focus transfer failed because from window did not have focus.");
4003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 return false;
4005 }
4006
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004007 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4008 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004009 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004010 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004011 CancelationOptions
4012 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4013 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 }
4017
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004018 if (DEBUG_FOCUS) {
4019 logDispatchStateLocked();
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 } // release lock
4022
4023 // Wake up poll loop since it may need to make new input dispatching choices.
4024 mLooper->wake();
4025 return true;
4026}
4027
4028void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004029 if (DEBUG_FOCUS) {
4030 ALOGD("Resetting and dropping all events (%s).", reason);
4031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032
4033 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4034 synthesizeCancelationEventsForAllConnectionsLocked(options);
4035
4036 resetKeyRepeatLocked();
4037 releasePendingEventLocked();
4038 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004039 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004041 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004042 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004044 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045}
4046
4047void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004048 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 dumpDispatchStateLocked(dump);
4050
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004051 std::istringstream stream(dump);
4052 std::string line;
4053
4054 while (std::getline(stream, line, '\n')) {
4055 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
4057}
4058
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004059void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004060 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4061 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4062 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004063 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
Tiger Huang721e26f2018-07-24 22:26:19 +08004065 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4066 dump += StringPrintf(INDENT "FocusedApplications:\n");
4067 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4068 const int32_t displayId = it.first;
4069 const sp<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004070 const int64_t timeoutMillis = millis(
4071 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004073 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004074 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004077 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004079
4080 if (!mFocusedWindowHandlesByDisplay.empty()) {
4081 dump += StringPrintf(INDENT "FocusedWindows:\n");
4082 for (auto& it : mFocusedWindowHandlesByDisplay) {
4083 const int32_t displayId = it.first;
4084 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4086 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004087 }
4088 } else {
4089 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004092 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004093 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004094 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4095 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004096 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 state.displayId, toString(state.down), toString(state.split),
4098 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004099 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004100 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004101 for (size_t i = 0; i < state.windows.size(); i++) {
4102 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 dump += StringPrintf(INDENT4
4104 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4105 i, touchedWindow.windowHandle->getName().c_str(),
4106 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004107 }
4108 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004109 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004110 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004111 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004112 dump += INDENT3 "Portal windows:\n";
4113 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004114 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4116 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004117 }
4118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
4120 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004121 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 }
4123
Arthur Hungb92218b2018-08-14 12:00:21 +08004124 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004126 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004127 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004128 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004129 dump += INDENT2 "Windows:\n";
4130 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004131 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
Arthur Hungb92218b2018-08-14 12:00:21 +08004134 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004136 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4137 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004139 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 i, windowInfo->name.c_str(), windowInfo->displayId,
4141 windowInfo->portalToDisplayId,
4142 toString(windowInfo->paused),
4143 toString(windowInfo->hasFocus),
4144 toString(windowInfo->hasWallpaper),
4145 toString(windowInfo->visible),
4146 toString(windowInfo->canReceiveKeys),
4147 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004148 windowInfo->layoutParamsType, windowInfo->frameLeft,
4149 windowInfo->frameTop, windowInfo->frameRight,
4150 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4151 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004152 dumpRegion(dump, windowInfo->touchableRegion);
4153 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004154 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4155 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004157 millis(windowInfo->dispatchingTimeout));
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004158 dump += StringPrintf(INDENT4 " flags: %s\n",
4159 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4160 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004161 }
4162 } else {
4163 dump += INDENT2 "Windows: <none>\n";
4164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 }
4166 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004167 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
Michael Wright3dd60e22019-03-27 22:06:44 +00004170 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004172 const std::vector<Monitor>& monitors = it.second;
4173 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4174 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 }
4176 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004177 const std::vector<Monitor>& monitors = it.second;
4178 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4179 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004182 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 }
4184
4185 nsecs_t currentTime = now();
4186
4187 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004188 if (!mRecentQueue.empty()) {
4189 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4190 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004193 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 }
4198
4199 // Dump event currently being dispatched.
4200 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT "PendingEvent:\n";
4202 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004204 dump += StringPrintf(", age=%" PRId64 "ms\n",
4205 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209
4210 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004211 if (!mInboundQueue.empty()) {
4212 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4213 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004216 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 }
4218 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004222 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004224 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4225 const KeyReplacement& replacement = pair.first;
4226 int32_t newKeyCode = pair.second;
4227 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004229 }
4230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004232 }
4233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004234 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004236 for (const auto& pair : mConnectionsByFd) {
4237 const sp<Connection>& connection = pair.second;
4238 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004239 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004240 pair.first, connection->getInputChannelName().c_str(),
4241 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004242 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004244 if (!connection->outboundQueue.empty()) {
4245 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4246 connection->outboundQueue.size());
4247 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 dump.append(INDENT4);
4249 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004250 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4251 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004253 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 }
4255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 }
4258
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004259 if (!connection->waitQueue.empty()) {
4260 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4261 connection->waitQueue.size());
4262 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004263 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004266 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004268 ns2ms(currentTime - entry->eventEntry->eventTime),
4269 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
4271 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274 }
4275 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004276 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
4279 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004280 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4281 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004283 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 }
4285
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004286 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004287 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4288 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4289 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290}
4291
Michael Wright3dd60e22019-03-27 22:06:44 +00004292void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4293 const size_t numMonitors = monitors.size();
4294 for (size_t i = 0; i < numMonitors; i++) {
4295 const Monitor& monitor = monitors[i];
4296 const sp<InputChannel>& channel = monitor.inputChannel;
4297 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4298 dump += "\n";
4299 }
4300}
4301
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004302status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004304 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305#endif
4306
4307 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004308 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004309 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004310 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 return BAD_VALUE;
4314 }
4315
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004316 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
4318 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004319 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004320 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4323 } // release lock
4324
4325 // Wake the looper because some connections have changed.
4326 mLooper->wake();
4327 return OK;
4328}
4329
Michael Wright3dd60e22019-03-27 22:06:44 +00004330status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004332 { // acquire lock
4333 std::scoped_lock _l(mLock);
4334
4335 if (displayId < 0) {
4336 ALOGW("Attempted to register input monitor without a specified display.");
4337 return BAD_VALUE;
4338 }
4339
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004340 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004341 ALOGW("Attempted to register input monitor without an identifying token.");
4342 return BAD_VALUE;
4343 }
4344
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004345 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004346
4347 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004348 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004349 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004350
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 auto& monitorsByDisplay =
4352 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004353 monitorsByDisplay[displayId].emplace_back(inputChannel);
4354
4355 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004356 }
4357 // Wake the looper because some connections have changed.
4358 mLooper->wake();
4359 return OK;
4360}
4361
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4363#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004364 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365#endif
4366
4367 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
4370 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4371 if (status) {
4372 return status;
4373 }
4374 } // release lock
4375
4376 // Wake the poll loop because removing the connection may have changed the current
4377 // synchronization state.
4378 mLooper->wake();
4379 return OK;
4380}
4381
4382status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004384 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004385 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 return BAD_VALUE;
4389 }
4390
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004391 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004392 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004393
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 if (connection->monitor) {
4395 removeMonitorChannelLocked(inputChannel);
4396 }
4397
4398 mLooper->removeFd(inputChannel->getFd());
4399
4400 nsecs_t currentTime = now();
4401 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4402
4403 connection->status = Connection::STATUS_ZOMBIE;
4404 return OK;
4405}
4406
4407void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004408 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4409 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4410}
4411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004412void InputDispatcher::removeMonitorChannelLocked(
4413 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004414 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004416 std::vector<Monitor>& monitors = it->second;
4417 const size_t numMonitors = monitors.size();
4418 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 if (monitors[i].inputChannel == inputChannel) {
4420 monitors.erase(monitors.begin() + i);
4421 break;
4422 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 if (monitors.empty()) {
4425 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004426 } else {
4427 ++it;
4428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 }
4430}
4431
Michael Wright3dd60e22019-03-27 22:06:44 +00004432status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4433 { // acquire lock
4434 std::scoped_lock _l(mLock);
4435 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4436
4437 if (!foundDisplayId) {
4438 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4439 return BAD_VALUE;
4440 }
4441 int32_t displayId = foundDisplayId.value();
4442
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004443 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4444 mTouchStatesByDisplay.find(displayId);
4445 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4447 return BAD_VALUE;
4448 }
4449
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004450 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004451 std::optional<int32_t> foundDeviceId;
4452 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004453 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004454 foundDeviceId = state.deviceId;
4455 }
4456 }
4457 if (!foundDeviceId || !state.down) {
4458 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004460 return BAD_VALUE;
4461 }
4462 int32_t deviceId = foundDeviceId.value();
4463
4464 // Send cancel events to all the input channels we're stealing from.
4465 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004467 options.deviceId = deviceId;
4468 options.displayId = displayId;
4469 for (const TouchedWindow& window : state.windows) {
4470 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004471 if (channel != nullptr) {
4472 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4473 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004474 }
4475 // Then clear the current touch state so we stop dispatching to them as well.
4476 state.filterNonMonitors();
4477 }
4478 return OK;
4479}
4480
Michael Wright3dd60e22019-03-27 22:06:44 +00004481std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4482 const sp<IBinder>& token) {
4483 for (const auto& it : mGestureMonitorsByDisplay) {
4484 const std::vector<Monitor>& monitors = it.second;
4485 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004486 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004487 return it.first;
4488 }
4489 }
4490 }
4491 return std::nullopt;
4492}
4493
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004494sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004495 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004496 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004497 }
4498
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004499 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004500 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004501 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004502 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
4504 }
Robert Carr4e670e52018-08-15 13:26:12 -07004505
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004506 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507}
4508
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004509void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004511 removeByValue(mConnectionsByFd, connection);
4512}
4513
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004514void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4515 const sp<Connection>& connection, uint32_t seq,
4516 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004517 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4518 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 commandEntry->connection = connection;
4520 commandEntry->eventTime = currentTime;
4521 commandEntry->seq = seq;
4522 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004523 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524}
4525
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4527 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004529 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004531 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4532 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004534 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535}
4536
chaviw0c06c6e2019-01-09 13:27:07 -08004537void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004538 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004539 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4540 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004541 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4542 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004543 commandEntry->oldToken = oldToken;
4544 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004545 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004546}
4547
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004548void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4549 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4550 // is already healthy again. Don't raise ANR in this situation
4551 if (connection->waitQueue.empty()) {
4552 ALOGI("Not raising ANR because the connection %s has recovered",
4553 connection->inputChannel->getName().c_str());
4554 return;
4555 }
4556 /**
4557 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4558 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4559 * has changed. This could cause newer entries to time out before the already dispatched
4560 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4561 * processes the events linearly. So providing information about the oldest entry seems to be
4562 * most useful.
4563 */
4564 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4565 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4566 std::string reason =
4567 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4568 connection->inputChannel->getName().c_str(),
4569 ns2ms(currentWait),
4570 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004572 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4573 reason);
4574
4575 std::unique_ptr<CommandEntry> commandEntry =
4576 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4577 commandEntry->inputApplicationHandle = nullptr;
4578 commandEntry->inputChannel = connection->inputChannel;
4579 commandEntry->reason = std::move(reason);
4580 postCommandLocked(std::move(commandEntry));
4581}
4582
4583void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4584 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4585 application->getName().c_str());
4586
4587 updateLastAnrStateLocked(application, reason);
4588
4589 std::unique_ptr<CommandEntry> commandEntry =
4590 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4591 commandEntry->inputApplicationHandle = application;
4592 commandEntry->inputChannel = nullptr;
4593 commandEntry->reason = std::move(reason);
4594 postCommandLocked(std::move(commandEntry));
4595}
4596
4597void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4598 const std::string& reason) {
4599 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4600 updateLastAnrStateLocked(windowLabel, reason);
4601}
4602
4603void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4604 const std::string& reason) {
4605 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4606 updateLastAnrStateLocked(windowLabel, reason);
4607}
4608
4609void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4610 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004612 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 struct tm tm;
4614 localtime_r(&t, &tm);
4615 char timestr[64];
4616 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004617 mLastAnrState.clear();
4618 mLastAnrState += INDENT "ANR:\n";
4619 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4621 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004622 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623}
4624
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 mLock.unlock();
4627
4628 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4629
4630 mLock.lock();
4631}
4632
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 sp<Connection> connection = commandEntry->connection;
4635
4636 if (connection->status != Connection::STATUS_ZOMBIE) {
4637 mLock.unlock();
4638
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004639 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640
4641 mLock.lock();
4642 }
4643}
4644
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004645void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004646 sp<IBinder> oldToken = commandEntry->oldToken;
4647 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004648 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004649 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004650 mLock.lock();
4651}
4652
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004653void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004654 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004655 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 mLock.unlock();
4657
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004658 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004659 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660
4661 mLock.lock();
4662
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004663 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4665 } else {
4666 // stop waking up for events in this connection, it is already not responding
4667 sp<Connection> connection = getConnectionLocked(token);
4668 if (connection == nullptr) {
4669 return;
4670 }
4671 cancelEventsForAnrLocked(connection);
4672 }
4673}
4674
4675void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4676 const sp<IBinder>& connectionToken,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004677 std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004678 sp<Connection> connection = getConnectionLocked(connectionToken);
4679 if (connection == nullptr) {
4680 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4681 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004682 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004683 mAwaitedFocusedApplication = application;
4684 } else {
4685 // It's also possible that the connection already disappeared. No action necessary.
4686 }
4687 return;
4688 }
4689
4690 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004691 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692
4693 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004694 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 for (DispatchEntry* entry : connection->waitQueue) {
4696 if (newTimeout >= entry->timeoutTime) {
4697 // Already removed old entries when connection was marked unresponsive
4698 entry->timeoutTime = newTimeout;
4699 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4700 }
4701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702}
4703
4704void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4705 CommandEntry* commandEntry) {
4706 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004707 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708
4709 mLock.unlock();
4710
Michael Wright2b3c3302018-03-02 17:19:13 +00004711 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004712 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004713 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714 : nullptr;
4715 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004716 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4717 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004718 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
4721 mLock.lock();
4722
4723 if (delay < 0) {
4724 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4725 } else if (!delay) {
4726 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4727 } else {
4728 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4729 entry->interceptKeyWakeupTime = now() + delay;
4730 }
4731 entry->release();
4732}
4733
chaviwfd6d3512019-03-25 13:23:49 -07004734void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4735 mLock.unlock();
4736 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4737 mLock.lock();
4738}
4739
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740/**
4741 * Connection is responsive if it has no events in the waitQueue that are older than the
4742 * current time.
4743 */
4744static bool isConnectionResponsive(const Connection& connection) {
4745 const nsecs_t currentTime = now();
4746 for (const DispatchEntry* entry : connection.waitQueue) {
4747 if (entry->timeoutTime < currentTime) {
4748 return false;
4749 }
4750 }
4751 return true;
4752}
4753
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004756 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004758 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759
4760 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004761 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004762 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004763 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004765 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004766 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004767 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004768 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4769 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004770 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004771 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004772
4773 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004774 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004775 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4776 restartEvent =
4777 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004778 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004779 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4780 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4781 handled);
4782 } else {
4783 restartEvent = false;
4784 }
4785
4786 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004787 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004788 // contents of the wait queue to have been drained, so we need to double-check
4789 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004790 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4791 if (dispatchEntryIt != connection->waitQueue.end()) {
4792 dispatchEntry = *dispatchEntryIt;
4793 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 mAnrTracker.erase(dispatchEntry->timeoutTime,
4795 connection->inputChannel->getConnectionToken());
4796 if (!connection->responsive) {
4797 connection->responsive = isConnectionResponsive(*connection);
4798 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004799 traceWaitQueueLength(connection);
4800 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004801 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004802 traceOutboundQueueLength(connection);
4803 } else {
4804 releaseDispatchEntry(dispatchEntry);
4805 }
4806 }
4807
4808 // Start the next dispatch cycle for this connection.
4809 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810}
4811
4812bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004813 DispatchEntry* dispatchEntry,
4814 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004815 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004816 if (!handled) {
4817 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004818 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004819 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004820 return false;
4821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004823 // Get the fallback key state.
4824 // Clear it out after dispatching the UP.
4825 int32_t originalKeyCode = keyEntry->keyCode;
4826 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4827 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4828 connection->inputState.removeFallbackKey(originalKeyCode);
4829 }
4830
4831 if (handled || !dispatchEntry->hasForegroundTarget()) {
4832 // If the application handles the original key for which we previously
4833 // generated a fallback or if the window is not a foreground window,
4834 // then cancel the associated fallback key, if any.
4835 if (fallbackKeyCode != -1) {
4836 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004838 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004839 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4840 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4841 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004843 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004844 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845
4846 mLock.unlock();
4847
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004848 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
4851 mLock.lock();
4852
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004853 // Cancel the fallback key.
4854 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004856 "application handled the original non-fallback key "
4857 "or is no longer a foreground target, "
4858 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 options.keyCode = fallbackKeyCode;
4860 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004862 connection->inputState.removeFallbackKey(originalKeyCode);
4863 }
4864 } else {
4865 // If the application did not handle a non-fallback key, first check
4866 // that we are in a good state to perform unhandled key event processing
4867 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004868 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004869 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004871 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004872 "since this is not an initial down. "
4873 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4874 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004876 return false;
4877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004879 // Dispatch the unhandled key to the policy.
4880#if DEBUG_OUTBOUND_EVENT_DETAILS
4881 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004882 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4883 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004885 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004886
4887 mLock.unlock();
4888
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004889 bool fallback =
4890 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4891 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004892
4893 mLock.lock();
4894
4895 if (connection->status != Connection::STATUS_NORMAL) {
4896 connection->inputState.removeFallbackKey(originalKeyCode);
4897 return false;
4898 }
4899
4900 // Latch the fallback keycode for this key on an initial down.
4901 // The fallback keycode cannot change at any other point in the lifecycle.
4902 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004904 fallbackKeyCode = event.getKeyCode();
4905 } else {
4906 fallbackKeyCode = AKEYCODE_UNKNOWN;
4907 }
4908 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4909 }
4910
4911 ALOG_ASSERT(fallbackKeyCode != -1);
4912
4913 // Cancel the fallback key if the policy decides not to send it anymore.
4914 // We will continue to dispatch the key to the policy but we will no
4915 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004916 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4917 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004918#if DEBUG_OUTBOUND_EVENT_DETAILS
4919 if (fallback) {
4920 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004921 "as a fallback for %d, but on the DOWN it had requested "
4922 "to send %d instead. Fallback canceled.",
4923 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004924 } else {
4925 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004926 "but on the DOWN it had requested to send %d. "
4927 "Fallback canceled.",
4928 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004929 }
4930#endif
4931
4932 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4933 "canceling fallback, policy no longer desires it");
4934 options.keyCode = fallbackKeyCode;
4935 synthesizeCancelationEventsForConnectionLocked(connection, options);
4936
4937 fallback = false;
4938 fallbackKeyCode = AKEYCODE_UNKNOWN;
4939 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004940 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004941 }
4942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
4944#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004945 {
4946 std::string msg;
4947 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4948 connection->inputState.getFallbackKeys();
4949 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004953 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 }
4955#endif
4956
4957 if (fallback) {
4958 // Restart the dispatch cycle using the fallback key.
4959 keyEntry->eventTime = event.getEventTime();
4960 keyEntry->deviceId = event.getDeviceId();
4961 keyEntry->source = event.getSource();
4962 keyEntry->displayId = event.getDisplayId();
4963 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4964 keyEntry->keyCode = fallbackKeyCode;
4965 keyEntry->scanCode = event.getScanCode();
4966 keyEntry->metaState = event.getMetaState();
4967 keyEntry->repeatCount = event.getRepeatCount();
4968 keyEntry->downTime = event.getDownTime();
4969 keyEntry->syntheticRepeat = false;
4970
4971#if DEBUG_OUTBOUND_EVENT_DETAILS
4972 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004973 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4974 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975#endif
4976 return true; // restart the event
4977 } else {
4978#if DEBUG_OUTBOUND_EVENT_DETAILS
4979 ALOGD("Unhandled key event: No fallback key.");
4980#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004981
4982 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004983 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 }
4985 }
4986 return false;
4987}
4988
4989bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 DispatchEntry* dispatchEntry,
4991 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 return false;
4993}
4994
4995void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4996 mLock.unlock();
4997
4998 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4999
5000 mLock.lock();
5001}
5002
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005003KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5004 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005005 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005006 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5007 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005008 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005011void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5012 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 // TODO Write some statistics about how long we spend waiting.
5014}
5015
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005016/**
5017 * Report the touch event latency to the statsd server.
5018 * Input events are reported for statistics if:
5019 * - This is a touchscreen event
5020 * - InputFilter is not enabled
5021 * - Event is not injected or synthesized
5022 *
5023 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5024 * from getting aggregated with the "old" data.
5025 */
5026void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5027 REQUIRES(mLock) {
5028 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5029 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5030 if (!reportForStatistics) {
5031 return;
5032 }
5033
5034 if (mTouchStatistics.shouldReport()) {
5035 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5036 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5037 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5038 mTouchStatistics.reset();
5039 }
5040 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5041 mTouchStatistics.addValue(latencyMicros);
5042}
5043
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044void InputDispatcher::traceInboundQueueLengthLocked() {
5045 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005046 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
5048}
5049
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005050void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 if (ATRACE_ENABLED()) {
5052 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005053 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005054 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 }
5056}
5057
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005058void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 if (ATRACE_ENABLED()) {
5060 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005061 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005062 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
5064}
5065
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005066void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005067 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005069 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070 dumpDispatchStateLocked(dump);
5071
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005072 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005073 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005074 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 }
5076}
5077
5078void InputDispatcher::monitor() {
5079 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005080 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005082 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083}
5084
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005085/**
5086 * Wake up the dispatcher and wait until it processes all events and commands.
5087 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5088 * this method can be safely called from any thread, as long as you've ensured that
5089 * the work you are interested in completing has already been queued.
5090 */
5091bool InputDispatcher::waitForIdle() {
5092 /**
5093 * Timeout should represent the longest possible time that a device might spend processing
5094 * events and commands.
5095 */
5096 constexpr std::chrono::duration TIMEOUT = 100ms;
5097 std::unique_lock lock(mLock);
5098 mLooper->wake();
5099 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5100 return result == std::cv_status::no_timeout;
5101}
5102
Garfield Tane84e6f92019-08-29 17:28:41 -07005103} // namespace android::inputdispatcher