blob: 14f7caf671f42ed77cf25dfc34363f8afd266e43 [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
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 const PointerProperties* pointerProperties) {
164 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Motion event has invalid action code 0x%x", action);
166 return false;
167 }
168 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000169 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 return false;
172 }
173 BitSet32 pointerIdBits;
174 for (size_t i = 0; i < pointerCount; i++) {
175 int32_t id = pointerProperties[i].id;
176 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
178 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 return false;
180 }
181 if (pointerIdBits.hasBit(id)) {
182 ALOGE("Motion event has duplicate pointer id %d", id);
183 return false;
184 }
185 pointerIdBits.markBit(id);
186 }
187 return true;
188}
189
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800192 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return;
194 }
195
196 bool first = true;
197 Region::const_iterator cur = region.begin();
198 Region::const_iterator const tail = region.end();
199 while (cur != tail) {
200 if (first) {
201 first = false;
202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 cur++;
207 }
208}
209
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700210/**
211 * Find the entry in std::unordered_map by key, and return it.
212 * If the entry is not found, return a default constructed entry.
213 *
214 * Useful when the entries are vectors, since an empty vector will be returned
215 * if the entry is not found.
216 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
217 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700218template <typename K, typename V>
219static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700221 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800222}
223
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700224/**
225 * Find the entry in std::unordered_map by value, and remove it.
226 * If more than one entry has the same value, then all matching
227 * key-value pairs will be removed.
228 *
229 * Return true if at least one value has been removed.
230 */
231template <typename K, typename V>
232static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
233 bool removed = false;
234 for (auto it = map.begin(); it != map.end();) {
235 if (it->second == value) {
236 it = map.erase(it);
237 removed = true;
238 } else {
239 it++;
240 }
241 }
242 return removed;
243}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
chaviwaf87b3e2019-10-01 16:59:28 -0700245static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
246 if (first == second) {
247 return true;
248 }
249
250 if (first == nullptr || second == nullptr) {
251 return false;
252 }
253
254 return first->getToken() == second->getToken();
255}
256
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800257static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
258 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
259}
260
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000261static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
262 EventEntry* eventEntry,
263 int32_t inputTargetFlags) {
264 if (inputTarget.useDefaultPointerInfo()) {
265 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
266 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
267 inputTargetFlags, pointerInfo.xOffset,
268 pointerInfo.yOffset, inputTarget.globalScaleFactor,
269 pointerInfo.windowXScale, pointerInfo.windowYScale);
270 }
271
272 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
273 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
274
275 PointerCoords pointerCoords[motionEntry.pointerCount];
276
277 // Use the first pointer information to normalize all other pointers. This could be any pointer
278 // as long as all other pointers are normalized to the same value and the final DispatchEntry
279 // uses the offset and scale for the normalized pointer.
280 const PointerInfo& firstPointerInfo =
281 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
282
283 // Iterate through all pointers in the event to normalize against the first.
284 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
285 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
286 uint32_t pointerId = uint32_t(pointerProperties.id);
287 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
288
289 // The scale factor is the ratio of the current pointers scale to the normalized scale.
290 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
291 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
292
293 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
294 // First apply the current pointers offset to set the window at 0,0
295 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
296 // Next scale the coordinates.
297 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
298 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
299 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
300 -firstPointerInfo.yOffset);
301 }
302
303 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800304 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000305 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
306 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
307 motionEntry.metaState, motionEntry.buttonState,
308 motionEntry.classification, motionEntry.edgeFlags,
309 motionEntry.xPrecision, motionEntry.yPrecision,
310 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
311 motionEntry.downTime, motionEntry.pointerCount,
312 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
313 0 /* yOffset */);
314
315 if (motionEntry.injectionState) {
316 combinedMotionEntry->injectionState = motionEntry.injectionState;
317 combinedMotionEntry->injectionState->refCount += 1;
318 }
319
320 std::unique_ptr<DispatchEntry> dispatchEntry =
321 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
322 inputTargetFlags, firstPointerInfo.xOffset,
323 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
324 firstPointerInfo.windowXScale,
325 firstPointerInfo.windowYScale);
326 combinedMotionEntry->release();
327 return dispatchEntry;
328}
329
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700330static void addGestureMonitors(const std::vector<Monitor>& monitors,
331 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
332 float yOffset = 0) {
333 if (monitors.empty()) {
334 return;
335 }
336 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
337 for (const Monitor& monitor : monitors) {
338 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
339 }
340}
341
Gang Wang342c9272020-01-13 13:15:04 -0500342static std::array<uint8_t, 128> getRandomKey() {
343 std::array<uint8_t, 128> key;
344 if (RAND_bytes(key.data(), key.size()) != 1) {
345 LOG_ALWAYS_FATAL("Can't generate HMAC key");
346 }
347 return key;
348}
349
350// --- HmacKeyManager ---
351
352HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
353
354std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
355 size_t size;
356 switch (event.type) {
357 case VerifiedInputEvent::Type::KEY: {
358 size = sizeof(VerifiedKeyEvent);
359 break;
360 }
361 case VerifiedInputEvent::Type::MOTION: {
362 size = sizeof(VerifiedMotionEvent);
363 break;
364 }
365 }
Gang Wang342c9272020-01-13 13:15:04 -0500366 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700367 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500368}
369
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700370std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500371 // SHA256 always generates 32-bytes result
372 std::array<uint8_t, 32> hash;
373 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700374 uint8_t* result =
375 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500376 if (result == nullptr) {
377 ALOGE("Could not sign the data using HMAC");
378 return INVALID_HMAC;
379 }
380
381 if (hashLen != hash.size()) {
382 ALOGE("HMAC-SHA256 has unexpected length");
383 return INVALID_HMAC;
384 }
385
386 return hash;
387}
388
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389// --- InputDispatcher ---
390
Garfield Tan00f511d2019-06-12 16:55:40 -0700391InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
392 : mPolicy(policy),
393 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700394 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800395 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700396 mAppSwitchSawKeyDown(false),
397 mAppSwitchDueTime(LONG_LONG_MAX),
398 mNextUnblockedEvent(nullptr),
399 mDispatchEnabled(false),
400 mDispatchFrozen(false),
401 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800402 // mInTouchMode will be initialized by the WindowManager to the default device config.
403 // To avoid leaking stack in case that call never comes, and for tests,
404 // initialize it here anyways.
405 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800408 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
Yi Kong9b14ac62018-07-17 13:48:38 -0700410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 policy->getDispatcherConfiguration(&mConfig);
413}
414
415InputDispatcher::~InputDispatcher() {
416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
426 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 }
428}
429
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700431 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return ALREADY_EXISTS;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437}
438
439status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return INVALID_OPERATION;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread.reset();
445 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446}
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482}
483
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700484/**
485 * Check if any of the connections' wait queues have events that are too old.
486 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
487 * Return the time at which we should wake up next.
488 */
489nsecs_t InputDispatcher::processAnrsLocked() {
490 const nsecs_t currentTime = now();
491 nsecs_t nextAnrCheck = LONG_LONG_MAX;
492 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
493 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
494 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
495 onAnrLocked(mAwaitedFocusedApplication);
496 mAwaitedFocusedApplication.clear();
497 return LONG_LONG_MIN;
498 } else {
499 // Keep waiting
500 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
501 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
502 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
503 }
504 }
505
506 // Check if any connection ANRs are due
507 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
508 if (currentTime < nextAnrCheck) { // most likely scenario
509 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
510 }
511
512 // If we reached here, we have an unresponsive connection.
513 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
514 if (connection == nullptr) {
515 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
516 return nextAnrCheck;
517 }
518 connection->responsive = false;
519 // Stop waking up for this unresponsive connection
520 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
521 onAnrLocked(connection);
522 return LONG_LONG_MIN;
523}
524
525nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
526 sp<InputWindowHandle> window = getWindowHandleLocked(token);
527 if (window != nullptr) {
528 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
529 }
530 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
531}
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
534 nsecs_t currentTime = now();
535
Jeff Browndc5992e2014-04-11 01:27:26 -0700536 // Reset the key repeat timer whenever normal dispatch is suspended while the
537 // device is in a non-interactive state. This is to ensure that we abort a key
538 // repeat if the device is just coming out of sleep.
539 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 resetKeyRepeatLocked();
541 }
542
543 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
544 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100545 if (DEBUG_FOCUS) {
546 ALOGD("Dispatch frozen. Waiting some more.");
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 return;
549 }
550
551 // Optimize latency of app switches.
552 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
553 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
554 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
555 if (mAppSwitchDueTime < *nextWakeupTime) {
556 *nextWakeupTime = mAppSwitchDueTime;
557 }
558
559 // Ready to start a new event.
560 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700561 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700562 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 if (isAppSwitchDue) {
564 // The inbound queue is empty so the app switch key we were waiting
565 // for will never arrive. Stop waiting for it.
566 resetPendingAppSwitchLocked(false);
567 isAppSwitchDue = false;
568 }
569
570 // Synthesize a key repeat if appropriate.
571 if (mKeyRepeatState.lastKeyEntry) {
572 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
573 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
574 } else {
575 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
576 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
577 }
578 }
579 }
580
581 // Nothing to do if there is no pending event.
582 if (!mPendingEvent) {
583 return;
584 }
585 } else {
586 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700587 mPendingEvent = mInboundQueue.front();
588 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 traceInboundQueueLengthLocked();
590 }
591
592 // Poke user activity for this event.
593 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597
598 // Now we have an event to dispatch.
599 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700600 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 }
608
609 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700614 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ConfigurationChangedEntry* typedEntry =
616 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
617 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 break;
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700622 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
624 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 break;
627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100629 case EventEntry::Type::FOCUS: {
630 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
631 dispatchFocusLocked(currentTime, typedEntry);
632 done = true;
633 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
634 break;
635 }
636
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700637 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
639 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 resetPendingAppSwitchLocked(true);
642 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700643 } else if (dropReason == DropReason::NOT_DROPPED) {
644 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 }
646 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700650 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
651 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 }
653 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
654 break;
655 }
656
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700657 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700659 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
660 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700662 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
666 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 }
668 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
672
673 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
Michael Wright3a981722015-06-10 15:26:13 +0100677 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678
679 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682}
683
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700684/**
685 * Return true if the events preceding this incoming motion event should be dropped
686 * Return false otherwise (the default behaviour)
687 */
688bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700690 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691
692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
696 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700697 int32_t displayId = motionEntry.displayId;
698 int32_t x = static_cast<int32_t>(
699 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
700 int32_t y = static_cast<int32_t>(
701 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
702 sp<InputWindowHandle> touchedWindowHandle =
703 findTouchedWindowAtLocked(displayId, x, y, nullptr);
704 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 touchedWindowHandle->getApplicationToken() !=
706 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700707 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 ALOGI("Pruning input queue because user touched a different application while waiting "
709 "for %s",
710 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700711 return true;
712 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713
714 // Alternatively, maybe there's a gesture monitor that could handle this event
715 std::vector<TouchedMonitor> gestureMonitors =
716 findTouchedGestureMonitorsLocked(displayId, {});
717 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
718 sp<Connection> connection =
719 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000720 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 // This monitor could take more input. Drop all events preceding this
722 // event, so that gesture monitor could get a chance to receive the stream
723 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
724 "responsive gesture monitor that may handle the event",
725 mAwaitedFocusedApplication->getName().c_str());
726 return true;
727 }
728 }
729 }
730
731 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
732 // yet been processed by some connections, the dispatcher will wait for these motion
733 // events to be processed before dispatching the key event. This is because these motion events
734 // may cause a new window to be launched, which the user might expect to receive focus.
735 // To prevent waiting forever for such events, just send the key to the currently focused window
736 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
737 ALOGD("Received a new pointer down event, stop waiting for events to process and "
738 "just send the pending key event to the focused window.");
739 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700740 }
741 return false;
742}
743
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 bool needWake = mInboundQueue.empty();
746 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748
749 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700750 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 // Optimize app switch latency.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700754 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700756 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 mAppSwitchSawKeyDown = false;
765 needWake = true;
766 }
767 }
768 }
769 break;
770 }
771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700773 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
774 mNextUnblockedEvent = entry;
775 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700780 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
781 break;
782 }
783 case EventEntry::Type::CONFIGURATION_CHANGED:
784 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 // nothing to do
786 break;
787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 return needWake;
791}
792
793void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
794 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mRecentQueue.push_back(entry);
796 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
797 mRecentQueue.front()->release();
798 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700803 int32_t y, TouchState* touchState,
804 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700806 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
807 LOG_ALWAYS_FATAL(
808 "Must provide a valid touch state if adding portal windows or outside targets");
809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800811 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
812 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
814 if (windowInfo->displayId == displayId) {
815 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816
817 if (windowInfo->visible) {
818 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 bool isTouchModal = (flags &
820 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
821 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800823 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 if (portalToDisplayId != ADISPLAY_ID_NONE &&
825 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800826 if (addPortalWindows) {
827 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700828 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800829 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700830 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 // Found window.
834 return windowHandle;
835 }
836 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800837
838 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700839 touchState->addOrUpdateWindow(windowHandle,
840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
841 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
845 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700846 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847}
848
Garfield Tane84e6f92019-08-29 17:28:41 -0700849std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700850 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000851 std::vector<TouchedMonitor> touchedMonitors;
852
853 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
854 addGestureMonitors(monitors, touchedMonitors);
855 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
856 const InputWindowInfo* windowInfo = portalWindow->getInfo();
857 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
859 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000860 }
861 return touchedMonitors;
862}
863
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700864void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 const char* reason;
866 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 reason = "inbound event was dropped because the policy consumed it";
872 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 case DropReason::DISABLED:
874 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 ALOGI("Dropped event because input dispatch is disabled.");
876 }
877 reason = "inbound event was dropped because input dispatch is disabled";
878 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 ALOGI("Dropped event because of pending overdue app switch.");
881 reason = "inbound event was dropped because of pending overdue app switch";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because the current application is not responding and the user "
885 "has started interacting with a different application.");
886 reason = "inbound event was dropped because the current application is not responding "
887 "and the user has started interacting with a different application";
888 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 ALOGI("Dropped event because it is stale.");
891 reason = "inbound event was dropped because it is stale";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::NOT_DROPPED: {
894 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700899 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
902 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700906 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
907 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
909 synthesizeCancelationEventsForAllConnectionsLocked(options);
910 } else {
911 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
912 synthesizeCancelationEventsForAllConnectionsLocked(options);
913 }
914 break;
915 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100916 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700917 case EventEntry::Type::CONFIGURATION_CHANGED:
918 case EventEntry::Type::DEVICE_RESET: {
919 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
920 break;
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923}
924
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800925static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
927 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928}
929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700930bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
931 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
932 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
933 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934}
935
936bool InputDispatcher::isAppSwitchPendingLocked() {
937 return mAppSwitchDueTime != LONG_LONG_MAX;
938}
939
940void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
941 mAppSwitchDueTime = LONG_LONG_MAX;
942
943#if DEBUG_APP_SWITCH
944 if (handled) {
945 ALOGD("App switch has arrived.");
946 } else {
947 ALOGD("App switch was abandoned.");
948 }
949#endif
950}
951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700953 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954}
955
956bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 return false;
959 }
960
961 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700962 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700963 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 return true;
970}
971
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700972void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
973 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974}
975
976void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 while (!mInboundQueue.empty()) {
978 EventEntry* entry = mInboundQueue.front();
979 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 releaseInboundEventLocked(entry);
981 }
982 traceInboundQueueLengthLocked();
983}
984
985void InputDispatcher::releasePendingEventLocked() {
986 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700988 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990}
991
992void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
993 InjectionState* injectionState = entry->injectionState;
994 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
995#if DEBUG_DISPATCH_CYCLE
996 ALOGD("Injected inbound event was dropped.");
997#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800998 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001001 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003 addRecentEventLocked(entry);
1004 entry->release();
1005}
1006
1007void InputDispatcher::resetKeyRepeatLocked() {
1008 if (mKeyRepeatState.lastKeyEntry) {
1009 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012}
1013
Garfield Tane84e6f92019-08-29 17:28:41 -07001014KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1016
1017 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001018 uint32_t policyFlags = entry->policyFlags &
1019 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 if (entry->refCount == 1) {
1021 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001022 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 entry->eventTime = currentTime;
1024 entry->policyFlags = policyFlags;
1025 entry->repeatCount += 1;
1026 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001028 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001029 entry->displayId, policyFlags, entry->action, entry->flags,
1030 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
1033 mKeyRepeatState.lastKeyEntry = newEntry;
1034 entry->release();
1035
1036 entry = newEntry;
1037 }
1038 entry->syntheticRepeat = true;
1039
1040 // Increment reference count since we keep a reference to the event in
1041 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1042 entry->refCount += 1;
1043
1044 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1045 return entry;
1046}
1047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1049 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001051 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052#endif
1053
1054 // Reset key repeating in case a keyboard device was added or removed or something.
1055 resetKeyRepeatLocked();
1056
1057 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001058 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1059 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001061 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 return true;
1063}
1064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001067 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069#endif
1070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 options.deviceId = entry->deviceId;
1073 synthesizeCancelationEventsForAllConnectionsLocked(options);
1074 return true;
1075}
1076
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001077void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001078 if (mPendingEvent != nullptr) {
1079 // Move the pending event to the front of the queue. This will give the chance
1080 // for the pending event to get dispatched to the newly focused window
1081 mInboundQueue.push_front(mPendingEvent);
1082 mPendingEvent = nullptr;
1083 }
1084
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001086 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001087
1088 // This event should go to the front of the queue, but behind all other focus events
1089 // Find the last focus event, and insert right after it
1090 std::deque<EventEntry*>::reverse_iterator it =
1091 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1092 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1093
1094 // Maintain the order of focus events. Insert the entry after all other focus events.
1095 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001096}
1097
1098void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1099 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1100 if (channel == nullptr) {
1101 return; // Window has gone away
1102 }
1103 InputTarget target;
1104 target.inputChannel = channel;
1105 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1106 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001107
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001108 dispatchEventLocked(currentTime, entry, {target});
1109}
1110
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 if (!entry->dispatchInProgress) {
1115 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1116 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1117 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1118 if (mKeyRepeatState.lastKeyEntry &&
1119 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // We have seen two identical key downs in a row which indicates that the device
1121 // driver is automatically generating key repeats itself. We take note of the
1122 // repeat here, but we disable our own next key repeat timer since it is clear that
1123 // we will not need to synthesize key repeats ourselves.
1124 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1125 resetKeyRepeatLocked();
1126 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1127 } else {
1128 // Not a repeat. Save key down state in case we do see a repeat later.
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1131 }
1132 mKeyRepeatState.lastKeyEntry = entry;
1133 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 resetKeyRepeatLocked();
1136 }
1137
1138 if (entry->repeatCount == 1) {
1139 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1140 } else {
1141 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1142 }
1143
1144 entry->dispatchInProgress = true;
1145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001146 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
1149 // Handle case where the policy asked us to try again later last time.
1150 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1151 if (currentTime < entry->interceptKeyWakeupTime) {
1152 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1153 *nextWakeupTime = entry->interceptKeyWakeupTime;
1154 }
1155 return false; // wait until next wakeup
1156 }
1157 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1158 entry->interceptKeyWakeupTime = 0;
1159 }
1160
1161 // Give the policy a chance to intercept the key.
1162 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1163 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001165 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001168 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 entry->refCount += 1;
1174 return false; // wait for the command to run
1175 } else {
1176 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1177 }
1178 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001179 if (*dropReason == DropReason::NOT_DROPPED) {
1180 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 }
1183
1184 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001185 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001186 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001189 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 return true;
1191 }
1192
1193 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001194 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1198 return false;
1199 }
1200
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001201 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1203 return true;
1204 }
1205
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001206 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
1209 // Dispatch the key.
1210 dispatchEventLocked(currentTime, entry, inputTargets);
1211 return true;
1212}
1213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001216 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1218 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1220 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1221 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222#endif
1223}
1224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1226 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001227 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 entry->dispatchInProgress = true;
1231
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234
1235 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001236 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001238 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 return true;
1241 }
1242
1243 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1244
1245 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001246 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
1248 bool conflictingPointerActions = false;
1249 int32_t injectionResult;
1250 if (isPointerEvent) {
1251 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001253 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 } else {
1256 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1261 return false;
1262 }
1263
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001264 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001265 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1266 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1267 return true;
1268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001270 CancelationOptions::Mode mode(isPointerEvent
1271 ? CancelationOptions::CANCEL_POINTER_EVENTS
1272 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1273 CancelationOptions options(mode, "input event injection failed");
1274 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 return true;
1276 }
1277
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001278 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001279 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001281 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001282 std::unordered_map<int32_t, TouchState>::iterator it =
1283 mTouchStatesByDisplay.find(entry->displayId);
1284 if (it != mTouchStatesByDisplay.end()) {
1285 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001286 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001287 // The event has gone through these portal windows, so we add monitoring targets of
1288 // the corresponding displays as well.
1289 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001291 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001293 }
1294 }
1295 }
1296 }
1297
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 // Dispatch the motion.
1299 if (conflictingPointerActions) {
1300 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 synthesizeCancelationEventsForAllConnectionsLocked(options);
1303 }
1304 dispatchEventLocked(currentTime, entry, inputTargets);
1305 return true;
1306}
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001310 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 ", policyFlags=0x%x, "
1312 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1313 "metaState=0x%x, buttonState=0x%x,"
1314 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1316 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1317 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 "x=%f, y=%f, pressure=%f, size=%f, "
1322 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1323 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1325 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1326 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1327 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1328 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335#endif
1336}
1337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1339 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001340 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341#if DEBUG_DISPATCH_CYCLE
1342 ALOGD("dispatchEventToCurrentInputTargets");
1343#endif
1344
1345 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1346
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001349 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001350 sp<Connection> connection =
1351 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001352 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001353 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001355 if (DEBUG_FOCUS) {
1356 ALOGD("Dropping event delivery to target with channel '%s' because it "
1357 "is no longer registered with the input dispatcher.",
1358 inputTarget.inputChannel->getName().c_str());
1359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361 }
1362}
1363
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001364void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1365 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1366 // If the policy decides to close the app, we will get a channel removal event via
1367 // unregisterInputChannel, and will clean up the connection that way. We are already not
1368 // sending new pointers to the connection when it blocked, but focused events will continue to
1369 // pile up.
1370 ALOGW("Canceling events for %s because it is unresponsive",
1371 connection->inputChannel->getName().c_str());
1372 if (connection->status == Connection::STATUS_NORMAL) {
1373 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1374 "application not responding");
1375 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377}
1378
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001379void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001380 if (DEBUG_FOCUS) {
1381 ALOGD("Resetting ANR timeouts.");
1382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383
1384 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001385 mNoFocusedWindowTimeoutTime = std::nullopt;
1386 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387}
1388
Tiger Huang721e26f2018-07-24 22:26:19 +08001389/**
1390 * Get the display id that the given event should go to. If this event specifies a valid display id,
1391 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1392 * Focused display is the display that the user most recently interacted with.
1393 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001394int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001395 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001397 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1399 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 break;
1401 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001402 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001403 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1404 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001405 break;
1406 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001407 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
1410 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 return ADISPLAY_ID_NONE;
1412 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001413 }
1414 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1415}
1416
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001417bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1418 const char* focusedWindowName) {
1419 if (mAnrTracker.empty()) {
1420 // already processed all events that we waited for
1421 mKeyIsWaitingForEventsTimeout = std::nullopt;
1422 return false;
1423 }
1424
1425 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1426 // Start the timer
1427 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1428 "focus to change",
1429 focusedWindowName);
1430 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1431 return true;
1432 }
1433
1434 // We still have pending events, and already started the timer
1435 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1436 return true; // Still waiting
1437 }
1438
1439 // Waited too long, and some connection still hasn't processed all motions
1440 // Just send the key to the focused window
1441 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1442 focusedWindowName);
1443 mKeyIsWaitingForEventsTimeout = std::nullopt;
1444 return false;
1445}
1446
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 std::vector<InputTarget>& inputTargets,
1450 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001451 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452
Tiger Huang721e26f2018-07-24 22:26:19 +08001453 int32_t displayId = getTargetDisplayId(entry);
1454 sp<InputWindowHandle> focusedWindowHandle =
1455 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1456 sp<InputApplicationHandle> focusedApplicationHandle =
1457 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 // If there is no currently focused window and no focused application
1460 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001461 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1462 ALOGI("Dropping %s event because there is no focused window or focused application in "
1463 "display %" PRId32 ".",
1464 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001465 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001468 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1469 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1470 // start interacting with another application via touch (app switch). This code can be removed
1471 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1472 // an app is expected to have a focused window.
1473 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1474 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1475 // We just discovered that there's no focused window. Start the ANR timer
1476 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1477 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1478 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1479 mAwaitedFocusedApplication = focusedApplicationHandle;
1480 ALOGW("Waiting because no window has focus but %s may eventually add a "
1481 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1482 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1483 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1484 return INPUT_EVENT_INJECTION_PENDING;
1485 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1486 // Already raised ANR. Drop the event
1487 ALOGE("Dropping %s event because there is no focused window",
1488 EventEntry::typeToString(entry.type));
1489 return INPUT_EVENT_INJECTION_FAILED;
1490 } else {
1491 // Still waiting for the focused window
1492 return INPUT_EVENT_INJECTION_PENDING;
1493 }
1494 }
1495
1496 // we have a valid, non-null focused window
1497 resetNoFocusedWindowTimeoutLocked();
1498
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001500 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001501 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001504 if (focusedWindowHandle->getInfo()->paused) {
1505 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1506 return INPUT_EVENT_INJECTION_PENDING;
1507 }
1508
1509 // If the event is a key event, then we must wait for all previous events to
1510 // complete before delivering it because previous events may have the
1511 // side-effect of transferring focus to a different window and we want to
1512 // ensure that the following keys are sent to the new window.
1513 //
1514 // Suppose the user touches a button in a window then immediately presses "A".
1515 // If the button causes a pop-up window to appear then we want to ensure that
1516 // the "A" key is delivered to the new pop-up window. This is because users
1517 // often anticipate pending UI changes when typing on a keyboard.
1518 // To obtain this behavior, we must serialize key events with respect to all
1519 // prior input events.
1520 if (entry.type == EventEntry::Type::KEY) {
1521 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1522 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1523 return INPUT_EVENT_INJECTION_PENDING;
1524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526
1527 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001528 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001529 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1530 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531
1532 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001533 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534}
1535
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001536/**
1537 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1538 * that are currently unresponsive.
1539 */
1540std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1541 const std::vector<TouchedMonitor>& monitors) const {
1542 std::vector<TouchedMonitor> responsiveMonitors;
1543 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1544 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1545 sp<Connection> connection = getConnectionLocked(
1546 monitor.monitor.inputChannel->getConnectionToken());
1547 if (connection == nullptr) {
1548 ALOGE("Could not find connection for monitor %s",
1549 monitor.monitor.inputChannel->getName().c_str());
1550 return false;
1551 }
1552 if (!connection->responsive) {
1553 ALOGW("Unresponsive monitor %s will not get the new gesture",
1554 connection->inputChannel->getName().c_str());
1555 return false;
1556 }
1557 return true;
1558 });
1559 return responsiveMonitors;
1560}
1561
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 std::vector<InputTarget>& inputTargets,
1565 nsecs_t* nextWakeupTime,
1566 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001567 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 enum InjectionPermission {
1569 INJECTION_PERMISSION_UNKNOWN,
1570 INJECTION_PERMISSION_GRANTED,
1571 INJECTION_PERMISSION_DENIED
1572 };
1573
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 // For security reasons, we defer updating the touch state until we are sure that
1575 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 int32_t displayId = entry.displayId;
1577 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1579
1580 // Update the touch state as needed based on the properties of the touch event.
1581 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1582 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1583 sp<InputWindowHandle> newHoverWindowHandle;
1584
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001585 // Copy current touch state into tempTouchState.
1586 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1587 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001588 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001589 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001590 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1591 mTouchStatesByDisplay.find(displayId);
1592 if (oldStateIt != mTouchStatesByDisplay.end()) {
1593 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001594 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001595 }
1596
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001597 bool isSplit = tempTouchState.split;
1598 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1599 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1600 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1602 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1603 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1604 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1605 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001606 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 bool wrongDevice = false;
1608 if (newGesture) {
1609 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001610 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001611 ALOGI("Dropping event because a pointer for a different device is already down "
1612 "in display %" PRId32,
1613 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001614 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1616 switchedDevice = false;
1617 wrongDevice = true;
1618 goto Failed;
1619 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001620 tempTouchState.reset();
1621 tempTouchState.down = down;
1622 tempTouchState.deviceId = entry.deviceId;
1623 tempTouchState.source = entry.source;
1624 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001626 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001627 ALOGI("Dropping move event because a pointer for a different device is already active "
1628 "in display %" PRId32,
1629 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001630 // TODO: test multiple simultaneous input streams.
1631 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1632 switchedDevice = false;
1633 wrongDevice = true;
1634 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 }
1636
1637 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1638 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1639
Garfield Tan00f511d2019-06-12 16:55:40 -07001640 int32_t x;
1641 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001643 // Always dispatch mouse events to cursor position.
1644 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001645 x = int32_t(entry.xCursorPosition);
1646 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001647 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1649 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001650 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001651 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001653 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1654 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001655
1656 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001657 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001658 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 if (newTouchedWindowHandle != nullptr &&
1662 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001663 // New window supports splitting, but we should never split mouse events.
1664 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 } else if (isSplit) {
1666 // New window does not support splitting but we have already split events.
1667 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001668 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
1671 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001672 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001674 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001675 }
1676
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001677 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1678 ALOGI("Not sending touch event to %s because it is paused",
1679 newTouchedWindowHandle->getName().c_str());
1680 newTouchedWindowHandle = nullptr;
1681 }
1682
1683 if (newTouchedWindowHandle != nullptr) {
1684 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1685 if (connection == nullptr) {
1686 ALOGI("Could not find connection for %s",
1687 newTouchedWindowHandle->getName().c_str());
1688 newTouchedWindowHandle = nullptr;
1689 } else if (!connection->responsive) {
1690 // don't send the new touch to an unresponsive window
1691 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1692 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1693 newTouchedWindowHandle = nullptr;
1694 }
1695 }
1696
1697 // Also don't send the new touch event to unresponsive gesture monitors
1698 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1699
Michael Wright3dd60e22019-03-27 22:06:44 +00001700 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1701 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001702 "(%d, %d) in display %" PRId32 ".",
1703 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1705 goto Failed;
1706 }
1707
1708 if (newTouchedWindowHandle != nullptr) {
1709 // Set target flags.
1710 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1711 if (isSplit) {
1712 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001714 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1715 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1716 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1717 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1718 }
1719
1720 // Update hover state.
1721 if (isHoverAction) {
1722 newHoverWindowHandle = newTouchedWindowHandle;
1723 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1724 newHoverWindowHandle = mLastHoverWindowHandle;
1725 }
1726
1727 // Update the temporary touch state.
1728 BitSet32 pointerIds;
1729 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001730 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 pointerIds.markBit(pointerId);
1732 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001733 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001736 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 } else {
1738 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1739
1740 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001742 if (DEBUG_FOCUS) {
1743 ALOGD("Dropping event because the pointer is not down or we previously "
1744 "dropped the pointer down event in display %" PRId32,
1745 displayId);
1746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1748 goto Failed;
1749 }
1750
1751 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001753 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1755 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
1757 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001758 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001760 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001761 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1762 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001763 if (DEBUG_FOCUS) {
1764 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1765 oldTouchedWindowHandle->getName().c_str(),
1766 newTouchedWindowHandle->getName().c_str(), displayId);
1767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001769 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1770 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1771 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
1773 // Make a slippery entrance into the new window.
1774 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1775 isSplit = true;
1776 }
1777
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 int32_t targetFlags =
1779 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 if (isSplit) {
1781 targetFlags |= InputTarget::FLAG_SPLIT;
1782 }
1783 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1784 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1785 }
1786
1787 BitSet32 pointerIds;
1788 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001791 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794 }
1795
1796 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1797 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001798 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799#if DEBUG_HOVER
1800 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001803 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1804 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 }
1806
1807 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001808 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#if DEBUG_HOVER
1810 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1814 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1815 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817 }
1818
1819 // Check permission to inject into all touched foreground windows and ensure there
1820 // is at least one touched foreground window.
1821 {
1822 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1825 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1828 injectionPermission = INJECTION_PERMISSION_DENIED;
1829 goto Failed;
1830 }
1831 }
1832 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001834 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001835 ALOGI("Dropping event because there is no touched foreground window in display "
1836 "%" PRId32 " or gesture monitor to receive it.",
1837 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1839 goto Failed;
1840 }
1841
1842 // Permission granted to injection into all touched foreground windows.
1843 injectionPermission = INJECTION_PERMISSION_GRANTED;
1844 }
1845
1846 // Check whether windows listening for outside touches are owned by the same UID. If it is
1847 // set the policy flag that we will not reveal coordinate information to this window.
1848 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1849 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001851 if (foregroundWindowHandle) {
1852 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001853 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001854 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1855 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1856 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1858 InputTarget::FLAG_ZERO_COORDS,
1859 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
1862 }
1863 }
1864 }
1865
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 // If this is the first pointer going down and the touched window has a wallpaper
1867 // then also add the touched wallpaper windows so they are locked in for the duration
1868 // of the touch gesture.
1869 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1870 // engine only supports touch events. We would need to add a mechanism similar
1871 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1872 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1873 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001874 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001875 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001876 const std::vector<sp<InputWindowHandle>> windowHandles =
1877 getWindowHandlesLocked(displayId);
1878 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 if (info->displayId == displayId &&
1881 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001882 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 .addOrUpdateWindow(windowHandle,
1884 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1885 InputTarget::
1886 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1887 InputTarget::FLAG_DISPATCH_AS_IS,
1888 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
1890 }
1891 }
1892 }
1893
1894 // Success! Output targets.
1895 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1896
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001897 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001899 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001902 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001903 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001904 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001905 }
1906
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 // Drop the outside or hover touch windows since we will not care about them
1908 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
1911Failed:
1912 // Check injection permission once and for all.
1913 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 injectionPermission = INJECTION_PERMISSION_GRANTED;
1916 } else {
1917 injectionPermission = INJECTION_PERMISSION_DENIED;
1918 }
1919 }
1920
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001921 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1922 return injectionResult;
1923 }
1924
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001926 if (!wrongDevice) {
1927 if (switchedDevice) {
1928 if (DEBUG_FOCUS) {
1929 ALOGD("Conflicting pointer actions: Switched to a different device.");
1930 }
1931 *outConflictingPointerActions = true;
1932 }
1933
1934 if (isHoverAction) {
1935 // Started hovering, therefore no longer down.
1936 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001937 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001938 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1939 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 *outConflictingPointerActions = true;
1942 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001943 tempTouchState.reset();
1944 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1945 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1946 tempTouchState.deviceId = entry.deviceId;
1947 tempTouchState.source = entry.source;
1948 tempTouchState.displayId = displayId;
1949 }
1950 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1951 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1952 // All pointers up or canceled.
1953 tempTouchState.reset();
1954 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1955 // First pointer went down.
1956 if (oldState && oldState->down) {
1957 if (DEBUG_FOCUS) {
1958 ALOGD("Conflicting pointer actions: Down received while already down.");
1959 }
1960 *outConflictingPointerActions = true;
1961 }
1962 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1963 // One pointer went up.
1964 if (isSplit) {
1965 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1966 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001968 for (size_t i = 0; i < tempTouchState.windows.size();) {
1969 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1970 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1971 touchedWindow.pointerIds.clearBit(pointerId);
1972 if (touchedWindow.pointerIds.isEmpty()) {
1973 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1974 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001977 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001979 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001980 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001981
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001982 // Save changes unless the action was scroll in which case the temporary touch
1983 // state was only valid for this one action.
1984 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1985 if (tempTouchState.displayId >= 0) {
1986 mTouchStatesByDisplay[displayId] = tempTouchState;
1987 } else {
1988 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 // Update hover state.
1993 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
1995
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 return injectionResult;
1997}
1998
1999void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002000 int32_t targetFlags, BitSet32 pointerIds,
2001 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002002 std::vector<InputTarget>::iterator it =
2003 std::find_if(inputTargets.begin(), inputTargets.end(),
2004 [&windowHandle](const InputTarget& inputTarget) {
2005 return inputTarget.inputChannel->getConnectionToken() ==
2006 windowHandle->getToken();
2007 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002008
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002009 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002010
2011 if (it == inputTargets.end()) {
2012 InputTarget inputTarget;
2013 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2014 if (inputChannel == nullptr) {
2015 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2016 return;
2017 }
2018 inputTarget.inputChannel = inputChannel;
2019 inputTarget.flags = targetFlags;
2020 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2021 inputTargets.push_back(inputTarget);
2022 it = inputTargets.end() - 1;
2023 }
2024
2025 ALOG_ASSERT(it->flags == targetFlags);
2026 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2027
2028 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2029 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030}
2031
Michael Wright3dd60e22019-03-27 22:06:44 +00002032void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002033 int32_t displayId, float xOffset,
2034 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2036 mGlobalMonitorsByDisplay.find(displayId);
2037
2038 if (it != mGlobalMonitorsByDisplay.end()) {
2039 const std::vector<Monitor>& monitors = it->second;
2040 for (const Monitor& monitor : monitors) {
2041 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044}
2045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2047 float yOffset,
2048 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 InputTarget target;
2050 target.inputChannel = monitor.inputChannel;
2051 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002052 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 inputTargets.push_back(target);
2054}
2055
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 const InjectionState* injectionState) {
2058 if (injectionState &&
2059 (windowHandle == nullptr ||
2060 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2061 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002062 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 "owned by uid %d",
2065 injectionState->injectorPid, injectionState->injectorUid,
2066 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 } else {
2068 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
2071 return false;
2072 }
2073 return true;
2074}
2075
Robert Carrc9bf1d32020-04-13 17:21:08 -07002076/**
2077 * Indicate whether one window handle should be considered as obscuring
2078 * another window handle. We only check a few preconditions. Actually
2079 * checking the bounds is left to the caller.
2080 */
2081static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2082 const sp<InputWindowHandle>& otherHandle) {
2083 // Compare by token so cloned layers aren't counted
2084 if (haveSameToken(windowHandle, otherHandle)) {
2085 return false;
2086 }
2087 auto info = windowHandle->getInfo();
2088 auto otherInfo = otherHandle->getInfo();
2089 if (!otherInfo->visible) {
2090 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002091 } else if (info->ownerPid == otherInfo->ownerPid) {
2092 // If ownerPid is the same we don't generate occlusion events as there
2093 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002094 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002095 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002096 return false;
2097 } else if (otherInfo->displayId != info->displayId) {
2098 return false;
2099 }
2100 return true;
2101}
2102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002103bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2104 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002106 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2107 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002108 if (windowHandle == otherHandle) {
2109 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002112 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002113 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 return true;
2115 }
2116 }
2117 return false;
2118}
2119
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002120bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2121 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002122 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002123 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002124 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002125 if (windowHandle == otherHandle) {
2126 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002127 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002128 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002129 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002130 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002131 return true;
2132 }
2133 }
2134 return false;
2135}
2136
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002137std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 const sp<InputApplicationHandle>& applicationHandle,
2139 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002140 if (applicationHandle != nullptr) {
2141 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002142 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 } else {
2144 return applicationHandle->getName();
2145 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002146 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002147 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002149 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151}
2152
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002153void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002154 if (eventEntry.type == EventEntry::Type::FOCUS) {
2155 // Focus events are passed to apps, but do not represent user activity.
2156 return;
2157 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002158 int32_t displayId = getTargetDisplayId(eventEntry);
2159 sp<InputWindowHandle> focusedWindowHandle =
2160 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2161 if (focusedWindowHandle != nullptr) {
2162 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2164#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002165 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166#endif
2167 return;
2168 }
2169 }
2170
2171 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002173 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2175 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 return;
2177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002179 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 eventType = USER_ACTIVITY_EVENT_TOUCH;
2181 }
2182 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002184 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002185 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2186 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 return;
2188 }
2189 eventType = USER_ACTIVITY_EVENT_BUTTON;
2190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002192 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002193 case EventEntry::Type::CONFIGURATION_CHANGED:
2194 case EventEntry::Type::DEVICE_RESET: {
2195 LOG_ALWAYS_FATAL("%s events are not user activity",
2196 EventEntry::typeToString(eventEntry.type));
2197 break;
2198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002201 std::unique_ptr<CommandEntry> commandEntry =
2202 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002205 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206}
2207
2208void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002209 const sp<Connection>& connection,
2210 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002211 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002212 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002214 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002215 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002216 ATRACE_NAME(message.c_str());
2217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218#if DEBUG_DISPATCH_CYCLE
2219 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002220 "globalScaleFactor=%f, pointerIds=0x%x %s",
2221 connection->getInputChannelName().c_str(), inputTarget.flags,
2222 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2223 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224#endif
2225
2226 // Skip this event if the connection status is not normal.
2227 // We don't want to enqueue additional outbound events if the connection is broken.
2228 if (connection->status != Connection::STATUS_NORMAL) {
2229#if DEBUG_DISPATCH_CYCLE
2230 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232#endif
2233 return;
2234 }
2235
2236 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002237 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2238 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2239 "Entry type %s should not have FLAG_SPLIT",
2240 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002242 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002243 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002245 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 if (!splitMotionEntry) {
2247 return; // split event was dropped
2248 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002249 if (DEBUG_FOCUS) {
2250 ALOGD("channel '%s' ~ Split motion event.",
2251 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002253 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 splitMotionEntry->release();
2256 return;
2257 }
2258 }
2259
2260 // Not splitting. Enqueue dispatch entries for the event as is.
2261 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2262}
2263
2264void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 const sp<Connection>& connection,
2266 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002267 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002270 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002271 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 ATRACE_NAME(message.c_str());
2273 }
2274
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002275 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276
2277 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290
2291 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002292 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 startDispatchCycleLocked(currentTime, connection);
2294 }
2295}
2296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2298 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002299 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002301 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2303 connection->getInputChannelName().c_str(),
2304 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 ATRACE_NAME(message.c_str());
2306 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002307 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 if (!(inputTargetFlags & dispatchMode)) {
2309 return;
2310 }
2311 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2312
2313 // This is a new event.
2314 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002315 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002316 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002318 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2319 // different EventEntry than what was passed in.
2320 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002322 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002323 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002324 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002325 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002326 dispatchEntry->resolvedAction = keyEntry.action;
2327 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2330 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2333 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 return; // skip the inconsistent event
2336 }
2337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002340 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002342 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2343 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2344 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2345 static_cast<int32_t>(IdGenerator::Source::OTHER);
2346 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2349 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2351 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2355 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2357 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002358 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002359 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 }
2361 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002362 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2363 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2366 "event",
2367 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2374 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2375 }
2376 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2377 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2381 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2384 "event",
2385 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 return; // skip the inconsistent event
2388 }
2389
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002390 dispatchEntry->resolvedEventId =
2391 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2392 ? mIdGenerator.nextId()
2393 : motionEntry.id;
2394 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2395 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2396 ") to MotionEvent(id=0x%" PRIx32 ").",
2397 motionEntry.id, dispatchEntry->resolvedEventId);
2398 ATRACE_NAME(message.c_str());
2399 }
2400
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002401 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002402 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002403
2404 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002406 case EventEntry::Type::FOCUS: {
2407 break;
2408 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002409 case EventEntry::Type::CONFIGURATION_CHANGED:
2410 case EventEntry::Type::DEVICE_RESET: {
2411 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002412 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002413 break;
2414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416
2417 // Remember that we are waiting for this dispatch to complete.
2418 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002419 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421
2422 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002423 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002424 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002425}
2426
chaviwfd6d3512019-03-25 13:23:49 -07002427void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002429 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002430 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2431 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002432 return;
2433 }
2434
2435 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2436 if (inputWindowHandle == nullptr) {
2437 return;
2438 }
2439
chaviw8c9cf542019-03-25 13:02:48 -07002440 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002441 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002442
2443 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2444
2445 if (!hasFocusChanged) {
2446 return;
2447 }
2448
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002449 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2450 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002451 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002452 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453}
2454
2455void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002457 if (ATRACE_ENABLED()) {
2458 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002460 ATRACE_NAME(message.c_str());
2461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464#endif
2465
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002466 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2467 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002469 const nsecs_t timeout =
2470 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2471 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
2473 // Publish the event.
2474 status_t status;
2475 EventEntry* eventEntry = dispatchEntry->eventEntry;
2476 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002477 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002478 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2479 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002482 status =
2483 connection->inputPublisher
2484 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2485 keyEntry->deviceId, keyEntry->source,
2486 keyEntry->displayId, std::move(hmac),
2487 dispatchEntry->resolvedAction,
2488 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2489 keyEntry->scanCode, keyEntry->metaState,
2490 keyEntry->repeatCount, keyEntry->downTime,
2491 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
2494
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002495 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 PointerCoords scaledCoords[MAX_POINTERS];
2499 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2500
chaviw82357092020-01-28 13:13:06 -08002501 // Set the X and Y offset and X and Y scale depending on the input source.
2502 float xOffset = 0.0f, yOffset = 0.0f;
2503 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2505 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2506 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002507 xScale = dispatchEntry->windowXScale;
2508 yScale = dispatchEntry->windowYScale;
2509 xOffset = dispatchEntry->xOffset * xScale;
2510 yOffset = dispatchEntry->yOffset * yScale;
2511 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2513 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002514 // Don't apply window scale here since we don't want scale to affect raw
2515 // coordinates. The scale will be sent back to the client and applied
2516 // later when requesting relative coordinates.
2517 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2518 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002519 }
2520 usingCoords = scaledCoords;
2521 }
2522 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 // We don't want the dispatch target to know.
2524 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2525 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2526 scaledCoords[i].clear();
2527 }
2528 usingCoords = scaledCoords;
2529 }
2530 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002531
2532 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533
2534 // Publish the motion event.
2535 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002536 .publishMotionEvent(dispatchEntry->seq,
2537 dispatchEntry->resolvedEventId,
2538 motionEntry->deviceId, motionEntry->source,
2539 motionEntry->displayId, std::move(hmac),
2540 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 motionEntry->actionButton,
2542 dispatchEntry->resolvedFlags,
2543 motionEntry->edgeFlags, motionEntry->metaState,
2544 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002545 motionEntry->classification, xScale, yScale,
2546 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 motionEntry->yPrecision,
2548 motionEntry->xCursorPosition,
2549 motionEntry->yCursorPosition,
2550 motionEntry->downTime, motionEntry->eventTime,
2551 motionEntry->pointerCount,
2552 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002553 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 break;
2555 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002556 case EventEntry::Type::FOCUS: {
2557 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2558 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002559 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002560 focusEntry->hasFocus,
2561 mInTouchMode);
2562 break;
2563 }
2564
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002565 case EventEntry::Type::CONFIGURATION_CHANGED:
2566 case EventEntry::Type::DEVICE_RESET: {
2567 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2568 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 }
2572
2573 // Check the result.
2574 if (status) {
2575 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002576 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 "This is unexpected because the wait queue is empty, so the pipe "
2579 "should be empty and we shouldn't have any problems writing an "
2580 "event to it, status=%d",
2581 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2583 } else {
2584 // Pipe is full and we are waiting for the app to finish process some events
2585 // before sending more events to it.
2586#if DEBUG_DISPATCH_CYCLE
2587 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 "waiting for the application to catch up",
2589 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
2592 } else {
2593 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 "status=%d",
2595 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2597 }
2598 return;
2599 }
2600
2601 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002602 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2603 connection->outboundQueue.end(),
2604 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002605 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002606 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002607 if (connection->responsive) {
2608 mAnrTracker.insert(dispatchEntry->timeoutTime,
2609 connection->inputChannel->getConnectionToken());
2610 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002611 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 }
2613}
2614
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002615const std::array<uint8_t, 32> InputDispatcher::getSignature(
2616 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2617 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2618 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2619 // Only sign events up and down events as the purely move events
2620 // are tied to their up/down counterparts so signing would be redundant.
2621 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2622 verifiedEvent.actionMasked = actionMasked;
2623 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2624 return mHmacKeyManager.sign(verifiedEvent);
2625 }
2626 return INVALID_HMAC;
2627}
2628
2629const std::array<uint8_t, 32> InputDispatcher::getSignature(
2630 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2631 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2632 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2633 verifiedEvent.action = dispatchEntry.resolvedAction;
2634 return mHmacKeyManager.sign(verifiedEvent);
2635}
2636
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002638 const sp<Connection>& connection, uint32_t seq,
2639 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640#if DEBUG_DISPATCH_CYCLE
2641 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643#endif
2644
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 if (connection->status == Connection::STATUS_BROKEN ||
2646 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 return;
2648 }
2649
2650 // Notify other system components and prepare to start the next dispatch cycle.
2651 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2652}
2653
2654void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 const sp<Connection>& connection,
2656 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657#if DEBUG_DISPATCH_CYCLE
2658 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660#endif
2661
2662 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002663 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002664 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002665 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002666 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667
2668 // The connection appears to be unrecoverably broken.
2669 // Ignore already broken or zombie connections.
2670 if (connection->status == Connection::STATUS_NORMAL) {
2671 connection->status = Connection::STATUS_BROKEN;
2672
2673 if (notify) {
2674 // Notify other system components.
2675 onDispatchCycleBrokenLocked(currentTime, connection);
2676 }
2677 }
2678}
2679
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002680void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2681 while (!queue.empty()) {
2682 DispatchEntry* dispatchEntry = queue.front();
2683 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002684 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 }
2686}
2687
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002688void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002690 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 }
2692 delete dispatchEntry;
2693}
2694
2695int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2696 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2697
2698 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002699 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002701 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703 "fd=%d, events=0x%x",
2704 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 return 0; // remove the callback
2706 }
2707
2708 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002709 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2711 if (!(events & ALOOPER_EVENT_INPUT)) {
2712 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002713 "events=0x%x",
2714 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 return 1;
2716 }
2717
2718 nsecs_t currentTime = now();
2719 bool gotOne = false;
2720 status_t status;
2721 for (;;) {
2722 uint32_t seq;
2723 bool handled;
2724 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2725 if (status) {
2726 break;
2727 }
2728 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2729 gotOne = true;
2730 }
2731 if (gotOne) {
2732 d->runCommandsLockedInterruptible();
2733 if (status == WOULD_BLOCK) {
2734 return 1;
2735 }
2736 }
2737
2738 notify = status != DEAD_OBJECT || !connection->monitor;
2739 if (notify) {
2740 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743 } else {
2744 // Monitor channels are never explicitly unregistered.
2745 // We do it automatically when the remote endpoint is closed so don't warn
2746 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002747 const bool stillHaveWindowHandle =
2748 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2749 nullptr;
2750 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 if (notify) {
2752 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 "events=0x%x",
2754 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756 }
2757
2758 // Unregister the channel.
2759 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2760 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762}
2763
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002766 for (const auto& pair : mConnectionsByFd) {
2767 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 }
2769}
2770
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002772 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002773 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2774 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2775}
2776
2777void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2778 const CancelationOptions& options,
2779 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2780 for (const auto& it : monitorsByDisplay) {
2781 const std::vector<Monitor>& monitors = it.second;
2782 for (const Monitor& monitor : monitors) {
2783 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002784 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002785 }
2786}
2787
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2789 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002790 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002791 if (connection == nullptr) {
2792 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002794
2795 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796}
2797
2798void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2799 const sp<Connection>& connection, const CancelationOptions& options) {
2800 if (connection->status == Connection::STATUS_BROKEN) {
2801 return;
2802 }
2803
2804 nsecs_t currentTime = now();
2805
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002806 std::vector<EventEntry*> cancelationEvents =
2807 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002809 if (cancelationEvents.empty()) {
2810 return;
2811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002813 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2814 "with reality: %s, mode=%d.",
2815 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2816 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002818
2819 InputTarget target;
2820 sp<InputWindowHandle> windowHandle =
2821 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2822 if (windowHandle != nullptr) {
2823 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2824 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2825 windowInfo->windowXScale, windowInfo->windowYScale);
2826 target.globalScaleFactor = windowInfo->globalScaleFactor;
2827 }
2828 target.inputChannel = connection->inputChannel;
2829 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2830
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002831 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2832 EventEntry* cancelationEventEntry = cancelationEvents[i];
2833 switch (cancelationEventEntry->type) {
2834 case EventEntry::Type::KEY: {
2835 logOutboundKeyDetails("cancel - ",
2836 static_cast<const KeyEntry&>(*cancelationEventEntry));
2837 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002839 case EventEntry::Type::MOTION: {
2840 logOutboundMotionDetails("cancel - ",
2841 static_cast<const MotionEntry&>(*cancelationEventEntry));
2842 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002844 case EventEntry::Type::FOCUS: {
2845 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2846 break;
2847 }
2848 case EventEntry::Type::CONFIGURATION_CHANGED:
2849 case EventEntry::Type::DEVICE_RESET: {
2850 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2851 EventEntry::typeToString(cancelationEventEntry->type));
2852 break;
2853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 }
2855
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002856 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2857 target, InputTarget::FLAG_DISPATCH_AS_IS);
2858
2859 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002861
2862 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863}
2864
Svet Ganov5d3bc372020-01-26 23:11:07 -08002865void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2866 const sp<Connection>& connection) {
2867 if (connection->status == Connection::STATUS_BROKEN) {
2868 return;
2869 }
2870
2871 nsecs_t currentTime = now();
2872
2873 std::vector<EventEntry*> downEvents =
2874 connection->inputState.synthesizePointerDownEvents(currentTime);
2875
2876 if (downEvents.empty()) {
2877 return;
2878 }
2879
2880#if DEBUG_OUTBOUND_EVENT_DETAILS
2881 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2882 connection->getInputChannelName().c_str(), downEvents.size());
2883#endif
2884
2885 InputTarget target;
2886 sp<InputWindowHandle> windowHandle =
2887 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2888 if (windowHandle != nullptr) {
2889 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2890 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2891 windowInfo->windowXScale, windowInfo->windowYScale);
2892 target.globalScaleFactor = windowInfo->globalScaleFactor;
2893 }
2894 target.inputChannel = connection->inputChannel;
2895 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2896
2897 for (EventEntry* downEventEntry : downEvents) {
2898 switch (downEventEntry->type) {
2899 case EventEntry::Type::MOTION: {
2900 logOutboundMotionDetails("down - ",
2901 static_cast<const MotionEntry&>(*downEventEntry));
2902 break;
2903 }
2904
2905 case EventEntry::Type::KEY:
2906 case EventEntry::Type::FOCUS:
2907 case EventEntry::Type::CONFIGURATION_CHANGED:
2908 case EventEntry::Type::DEVICE_RESET: {
2909 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2910 EventEntry::typeToString(downEventEntry->type));
2911 break;
2912 }
2913 }
2914
2915 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2916 target, InputTarget::FLAG_DISPATCH_AS_IS);
2917
2918 downEventEntry->release();
2919 }
2920
2921 startDispatchCycleLocked(currentTime, connection);
2922}
2923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002925 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 ALOG_ASSERT(pointerIds.value != 0);
2927
2928 uint32_t splitPointerIndexMap[MAX_POINTERS];
2929 PointerProperties splitPointerProperties[MAX_POINTERS];
2930 PointerCoords splitPointerCoords[MAX_POINTERS];
2931
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002932 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 uint32_t splitPointerCount = 0;
2934
2935 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 uint32_t pointerId = uint32_t(pointerProperties.id);
2940 if (pointerIds.hasBit(pointerId)) {
2941 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2942 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2943 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002944 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 splitPointerCount += 1;
2946 }
2947 }
2948
2949 if (splitPointerCount != pointerIds.count()) {
2950 // This is bad. We are missing some of the pointers that we expected to deliver.
2951 // Most likely this indicates that we received an ACTION_MOVE events that has
2952 // different pointer ids than we expected based on the previous ACTION_DOWN
2953 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2954 // in this way.
2955 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956 "we expected there to be %d pointers. This probably means we received "
2957 "a broken sequence of pointer ids from the input device.",
2958 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002959 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 }
2961
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002962 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2965 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2967 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 uint32_t pointerId = uint32_t(pointerProperties.id);
2970 if (pointerIds.hasBit(pointerId)) {
2971 if (pointerIds.count() == 1) {
2972 // The first/last pointer went down/up.
2973 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 ? AMOTION_EVENT_ACTION_DOWN
2975 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 } else {
2977 // A secondary pointer went down/up.
2978 uint32_t splitPointerIndex = 0;
2979 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2980 splitPointerIndex += 1;
2981 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 action = maskedAction |
2983 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985 } else {
2986 // An unrelated pointer changed.
2987 action = AMOTION_EVENT_ACTION_MOVE;
2988 }
2989 }
2990
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002991 int32_t newId = mIdGenerator.nextId();
2992 if (ATRACE_ENABLED()) {
2993 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2994 ") to MotionEvent(id=0x%" PRIx32 ").",
2995 originalMotionEntry.id, newId);
2996 ATRACE_NAME(message.c_str());
2997 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002998 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002999 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3000 originalMotionEntry.source, originalMotionEntry.displayId,
3001 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002 originalMotionEntry.actionButton, originalMotionEntry.flags,
3003 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3004 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3005 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3006 originalMotionEntry.xCursorPosition,
3007 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003008 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003010 if (originalMotionEntry.injectionState) {
3011 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 splitMotionEntry->injectionState->refCount += 1;
3013 }
3014
3015 return splitMotionEntry;
3016}
3017
3018void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3019#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003020 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021#endif
3022
3023 bool needWake;
3024 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026
Prabir Pradhan42611e02018-11-27 14:04:02 -08003027 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003028 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 needWake = enqueueInboundEventLocked(newEntry);
3030 } // release lock
3031
3032 if (needWake) {
3033 mLooper->wake();
3034 }
3035}
3036
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003037/**
3038 * If one of the meta shortcuts is detected, process them here:
3039 * Meta + Backspace -> generate BACK
3040 * Meta + Enter -> generate HOME
3041 * This will potentially overwrite keyCode and metaState.
3042 */
3043void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003045 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3046 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3047 if (keyCode == AKEYCODE_DEL) {
3048 newKeyCode = AKEYCODE_BACK;
3049 } else if (keyCode == AKEYCODE_ENTER) {
3050 newKeyCode = AKEYCODE_HOME;
3051 }
3052 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003053 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003054 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003055 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003056 keyCode = newKeyCode;
3057 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3058 }
3059 } else if (action == AKEY_EVENT_ACTION_UP) {
3060 // In order to maintain a consistent stream of up and down events, check to see if the key
3061 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3062 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003063 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003064 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003065 auto replacementIt = mReplacedKeys.find(replacement);
3066 if (replacementIt != mReplacedKeys.end()) {
3067 keyCode = replacementIt->second;
3068 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003069 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3070 }
3071 }
3072}
3073
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3075#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3077 "policyFlags=0x%x, action=0x%x, "
3078 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3079 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3080 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3081 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082#endif
3083 if (!validateKeyEvent(args->action)) {
3084 return;
3085 }
3086
3087 uint32_t policyFlags = args->policyFlags;
3088 int32_t flags = args->flags;
3089 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003090 // InputDispatcher tracks and generates key repeats on behalf of
3091 // whatever notifies it, so repeatCount should always be set to 0
3092 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3094 policyFlags |= POLICY_FLAG_VIRTUAL;
3095 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 if (policyFlags & POLICY_FLAG_FUNCTION) {
3098 metaState |= AMETA_FUNCTION_ON;
3099 }
3100
3101 policyFlags |= POLICY_FLAG_TRUSTED;
3102
Michael Wright78f24442014-08-06 15:55:28 -07003103 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003104 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003105
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003107 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003108 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3109 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
Michael Wright2b3c3302018-03-02 17:19:13 +00003111 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003113 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3114 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 bool needWake;
3119 { // acquire lock
3120 mLock.lock();
3121
3122 if (shouldSendKeyToInputFilterLocked(args)) {
3123 mLock.unlock();
3124
3125 policyFlags |= POLICY_FLAG_FILTERED;
3126 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3127 return; // event was consumed by the filter
3128 }
3129
3130 mLock.lock();
3131 }
3132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003134 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 args->displayId, policyFlags, args->action, flags, keyCode,
3136 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137
3138 needWake = enqueueInboundEventLocked(newEntry);
3139 mLock.unlock();
3140 } // release lock
3141
3142 if (needWake) {
3143 mLooper->wake();
3144 }
3145}
3146
3147bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3148 return mInputFilterEnabled;
3149}
3150
3151void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3152#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003153 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3154 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003155 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3156 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003157 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003158 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3159 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3160 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3161 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 for (uint32_t i = 0; i < args->pointerCount; i++) {
3163 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 "x=%f, y=%f, pressure=%f, size=%f, "
3165 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3166 "orientation=%f",
3167 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3168 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3169 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3170 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3171 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3180 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 return;
3182 }
3183
3184 uint32_t policyFlags = args->policyFlags;
3185 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003186
3187 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003188 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003189 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3190 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193
3194 bool needWake;
3195 { // acquire lock
3196 mLock.lock();
3197
3198 if (shouldSendMotionToInputFilterLocked(args)) {
3199 mLock.unlock();
3200
3201 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003202 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3203 args->action, args->actionButton, args->flags, args->edgeFlags,
3204 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3205 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3206 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3207 args->downTime, args->eventTime, args->pointerCount,
3208 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209
3210 policyFlags |= POLICY_FLAG_FILTERED;
3211 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3212 return; // event was consumed by the filter
3213 }
3214
3215 mLock.lock();
3216 }
3217
3218 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003219 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003220 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003221 args->displayId, policyFlags, args->action, args->actionButton,
3222 args->flags, args->metaState, args->buttonState,
3223 args->classification, args->edgeFlags, args->xPrecision,
3224 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3225 args->downTime, args->pointerCount, args->pointerProperties,
3226 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227
3228 needWake = enqueueInboundEventLocked(newEntry);
3229 mLock.unlock();
3230 } // release lock
3231
3232 if (needWake) {
3233 mLooper->wake();
3234 }
3235}
3236
3237bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003238 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3242#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003243 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 "switchMask=0x%08x",
3245 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246#endif
3247
3248 uint32_t policyFlags = args->policyFlags;
3249 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251}
3252
3253void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3254#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3256 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257#endif
3258
3259 bool needWake;
3260 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003261 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
Prabir Pradhan42611e02018-11-27 14:04:02 -08003263 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003264 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 needWake = enqueueInboundEventLocked(newEntry);
3266 } // release lock
3267
3268 if (needWake) {
3269 mLooper->wake();
3270 }
3271}
3272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3274 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003275 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276#if DEBUG_INBOUND_EVENT_DETAILS
3277 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003278 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3279 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#endif
3281
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003282 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 policyFlags |= POLICY_FLAG_INJECTED;
3285 if (hasInjectionPermission(injectorPid, injectorUid)) {
3286 policyFlags |= POLICY_FLAG_TRUSTED;
3287 }
3288
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003289 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003292 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3293 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 if (!validateKeyEvent(action)) {
3295 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003298 int32_t flags = incomingKey.getFlags();
3299 int32_t keyCode = incomingKey.getKeyCode();
3300 int32_t metaState = incomingKey.getMetaState();
3301 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003303 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003304 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003305 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3306 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3307 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3310 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003311 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312
3313 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3314 android::base::Timer t;
3315 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3316 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3317 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3318 std::to_string(t.duration().count()).c_str());
3319 }
3320 }
3321
3322 mLock.lock();
3323 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003324 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3325 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003326 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3327 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003328 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 injectedEntries.push(injectedEntry);
3330 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
3332
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 case AINPUT_EVENT_TYPE_MOTION: {
3334 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3335 int32_t action = motionEvent->getAction();
3336 size_t pointerCount = motionEvent->getPointerCount();
3337 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3338 int32_t actionButton = motionEvent->getActionButton();
3339 int32_t displayId = motionEvent->getDisplayId();
3340 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3341 return INPUT_EVENT_INJECTION_FAILED;
3342 }
3343
3344 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3345 nsecs_t eventTime = motionEvent->getEventTime();
3346 android::base::Timer t;
3347 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3348 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3349 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3350 std::to_string(t.duration().count()).c_str());
3351 }
3352 }
3353
3354 mLock.lock();
3355 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3356 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3357 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003358 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3359 motionEvent->getSource(), motionEvent->getDisplayId(),
3360 policyFlags, action, actionButton, motionEvent->getFlags(),
3361 motionEvent->getMetaState(), motionEvent->getButtonState(),
3362 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3363 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003364 motionEvent->getRawXCursorPosition(),
3365 motionEvent->getRawYCursorPosition(),
3366 motionEvent->getDownTime(), uint32_t(pointerCount),
3367 pointerProperties, samplePointerCoords,
3368 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 injectedEntries.push(injectedEntry);
3370 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3371 sampleEventTimes += 1;
3372 samplePointerCoords += pointerCount;
3373 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003374 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003375 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 motionEvent->getDisplayId(), policyFlags, action,
3377 actionButton, motionEvent->getFlags(),
3378 motionEvent->getMetaState(), motionEvent->getButtonState(),
3379 motionEvent->getClassification(),
3380 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3381 motionEvent->getYPrecision(),
3382 motionEvent->getRawXCursorPosition(),
3383 motionEvent->getRawYCursorPosition(),
3384 motionEvent->getDownTime(), uint32_t(pointerCount),
3385 pointerProperties, samplePointerCoords,
3386 motionEvent->getXOffset(), motionEvent->getYOffset());
3387 injectedEntries.push(nextInjectedEntry);
3388 }
3389 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003393 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 }
3396
3397 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3398 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3399 injectionState->injectionIsAsync = true;
3400 }
3401
3402 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003403 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404
3405 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003406 while (!injectedEntries.empty()) {
3407 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3408 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
3411 mLock.unlock();
3412
3413 if (needWake) {
3414 mLooper->wake();
3415 }
3416
3417 int32_t injectionResult;
3418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003419 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420
3421 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3422 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3423 } else {
3424 for (;;) {
3425 injectionResult = injectionState->injectionResult;
3426 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3427 break;
3428 }
3429
3430 nsecs_t remainingTimeout = endTime - now();
3431 if (remainingTimeout <= 0) {
3432#if DEBUG_INJECTION
3433 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435#endif
3436 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3437 break;
3438 }
3439
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003440 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
3442
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003443 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3444 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 while (injectionState->pendingForegroundDispatches != 0) {
3446#if DEBUG_INJECTION
3447 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449#endif
3450 nsecs_t remainingTimeout = endTime - now();
3451 if (remainingTimeout <= 0) {
3452#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3454 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455#endif
3456 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3457 break;
3458 }
3459
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003460 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462 }
3463 }
3464
3465 injectionState->release();
3466 } // release lock
3467
3468#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003469 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471#endif
3472
3473 return injectionResult;
3474}
3475
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003476std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003477 std::array<uint8_t, 32> calculatedHmac;
3478 std::unique_ptr<VerifiedInputEvent> result;
3479 switch (event.getType()) {
3480 case AINPUT_EVENT_TYPE_KEY: {
3481 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3482 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3483 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3484 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3485 break;
3486 }
3487 case AINPUT_EVENT_TYPE_MOTION: {
3488 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3489 VerifiedMotionEvent verifiedMotionEvent =
3490 verifiedMotionEventFromMotionEvent(motionEvent);
3491 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3492 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3493 break;
3494 }
3495 default: {
3496 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3497 return nullptr;
3498 }
3499 }
3500 if (calculatedHmac == INVALID_HMAC) {
3501 return nullptr;
3502 }
3503 if (calculatedHmac != event.getHmac()) {
3504 return nullptr;
3505 }
3506 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003507}
3508
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 return injectorUid == 0 ||
3511 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512}
3513
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003514void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 InjectionState* injectionState = entry->injectionState;
3516 if (injectionState) {
3517#if DEBUG_INJECTION
3518 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 "injectorPid=%d, injectorUid=%d",
3520 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521#endif
3522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 // Log the outcome since the injector did not wait for the injection result.
3525 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526 case INPUT_EVENT_INJECTION_SUCCEEDED:
3527 ALOGV("Asynchronous input event injection succeeded.");
3528 break;
3529 case INPUT_EVENT_INJECTION_FAILED:
3530 ALOGW("Asynchronous input event injection failed.");
3531 break;
3532 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3533 ALOGW("Asynchronous input event injection permission denied.");
3534 break;
3535 case INPUT_EVENT_INJECTION_TIMED_OUT:
3536 ALOGW("Asynchronous input event injection timed out.");
3537 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539 }
3540
3541 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003542 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544}
3545
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003546void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 InjectionState* injectionState = entry->injectionState;
3548 if (injectionState) {
3549 injectionState->pendingForegroundDispatches += 1;
3550 }
3551}
3552
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003553void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 InjectionState* injectionState = entry->injectionState;
3555 if (injectionState) {
3556 injectionState->pendingForegroundDispatches -= 1;
3557
3558 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003559 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561 }
3562}
3563
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003564std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3565 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003566 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003567}
3568
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003570 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003571 if (windowHandleToken == nullptr) {
3572 return nullptr;
3573 }
3574
Arthur Hungb92218b2018-08-14 12:00:21 +08003575 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003576 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3577 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003578 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003579 return windowHandle;
3580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 }
3582 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003583 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584}
3585
Mady Mellor017bcd12020-06-23 19:12:00 +00003586bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3587 for (auto& it : mWindowHandlesByDisplay) {
3588 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3589 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003590 if (handle->getId() == windowHandle->getId() &&
3591 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003592 if (windowHandle->getInfo()->displayId != it.first) {
3593 ALOGE("Found window %s in display %" PRId32
3594 ", but it should belong to display %" PRId32,
3595 windowHandle->getName().c_str(), it.first,
3596 windowHandle->getInfo()->displayId);
3597 }
3598 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
3601 }
3602 return false;
3603}
3604
Robert Carr5c8a0262018-10-03 16:30:44 -07003605sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3606 size_t count = mInputChannelsByToken.count(token);
3607 if (count == 0) {
3608 return nullptr;
3609 }
3610 return mInputChannelsByToken.at(token);
3611}
3612
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003613void InputDispatcher::updateWindowHandlesForDisplayLocked(
3614 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3615 if (inputWindowHandles.empty()) {
3616 // Remove all handles on a display if there are no windows left.
3617 mWindowHandlesByDisplay.erase(displayId);
3618 return;
3619 }
3620
3621 // Since we compare the pointer of input window handles across window updates, we need
3622 // to make sure the handle object for the same window stays unchanged across updates.
3623 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003624 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003625 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003626 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003627 }
3628
3629 std::vector<sp<InputWindowHandle>> newHandles;
3630 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3631 if (!handle->updateInfo()) {
3632 // handle no longer valid
3633 continue;
3634 }
3635
3636 const InputWindowInfo* info = handle->getInfo();
3637 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3638 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3639 const bool noInputChannel =
3640 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3641 const bool canReceiveInput =
3642 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3643 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3644 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003645 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003646 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003647 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003648 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003649 }
3650
3651 if (info->displayId != displayId) {
3652 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3653 handle->getName().c_str(), displayId, info->displayId);
3654 continue;
3655 }
3656
Robert Carredd13602020-04-13 17:24:34 -07003657 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3658 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003659 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003660 oldHandle->updateFrom(handle);
3661 newHandles.push_back(oldHandle);
3662 } else {
3663 newHandles.push_back(handle);
3664 }
3665 }
3666
3667 // Insert or replace
3668 mWindowHandlesByDisplay[displayId] = newHandles;
3669}
3670
Arthur Hung72d8dc32020-03-28 00:48:39 +00003671void InputDispatcher::setInputWindows(
3672 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3673 { // acquire lock
3674 std::scoped_lock _l(mLock);
3675 for (auto const& i : handlesPerDisplay) {
3676 setInputWindowsLocked(i.second, i.first);
3677 }
3678 }
3679 // Wake up poll loop since it may need to make new input dispatching choices.
3680 mLooper->wake();
3681}
3682
Arthur Hungb92218b2018-08-14 12:00:21 +08003683/**
3684 * Called from InputManagerService, update window handle list by displayId that can receive input.
3685 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3686 * If set an empty list, remove all handles from the specific display.
3687 * For focused handle, check if need to change and send a cancel event to previous one.
3688 * For removed handle, check if need to send a cancel event if already in touch.
3689 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003690void InputDispatcher::setInputWindowsLocked(
3691 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003692 if (DEBUG_FOCUS) {
3693 std::string windowList;
3694 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3695 windowList += iwh->getName() + " ";
3696 }
3697 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699
Arthur Hung72d8dc32020-03-28 00:48:39 +00003700 // Copy old handles for release if they are no longer present.
3701 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
Arthur Hung72d8dc32020-03-28 00:48:39 +00003703 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003704
Arthur Hung72d8dc32020-03-28 00:48:39 +00003705 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3706 bool foundHoveredWindow = false;
3707 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3708 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3709 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3710 windowHandle->getInfo()->visible) {
3711 newFocusedWindowHandle = windowHandle;
3712 }
3713 if (windowHandle == mLastHoverWindowHandle) {
3714 foundHoveredWindow = true;
3715 }
3716 }
3717
3718 if (!foundHoveredWindow) {
3719 mLastHoverWindowHandle = nullptr;
3720 }
3721
3722 sp<InputWindowHandle> oldFocusedWindowHandle =
3723 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3724
3725 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3726 if (oldFocusedWindowHandle != nullptr) {
3727 if (DEBUG_FOCUS) {
3728 ALOGD("Focus left window: %s in display %" PRId32,
3729 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003730 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003731 sp<InputChannel> focusedInputChannel =
3732 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3733 if (focusedInputChannel != nullptr) {
3734 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3735 "focus left window");
3736 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3737 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003738 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003739 mFocusedWindowHandlesByDisplay.erase(displayId);
3740 }
3741 if (newFocusedWindowHandle != nullptr) {
3742 if (DEBUG_FOCUS) {
3743 ALOGD("Focus entered window: %s in display %" PRId32,
3744 newFocusedWindowHandle->getName().c_str(), displayId);
3745 }
3746 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3747 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750 if (mFocusedDisplayId == displayId) {
3751 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003755 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3756 mTouchStatesByDisplay.find(displayId);
3757 if (stateIt != mTouchStatesByDisplay.end()) {
3758 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 for (size_t i = 0; i < state.windows.size();) {
3760 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003761 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003762 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003763 ALOGD("Touched window was removed: %s in display %" PRId32,
3764 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003765 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003766 sp<InputChannel> touchedInputChannel =
3767 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3768 if (touchedInputChannel != nullptr) {
3769 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3770 "touched window was removed");
3771 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 state.windows.erase(state.windows.begin() + i);
3774 } else {
3775 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 }
3777 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003778 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003779
Arthur Hung72d8dc32020-03-28 00:48:39 +00003780 // Release information for windows that are no longer present.
3781 // This ensures that unused input channels are released promptly.
3782 // Otherwise, they might stick around until the window handle is destroyed
3783 // which might not happen until the next GC.
3784 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003785 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003786 if (DEBUG_FOCUS) {
3787 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003788 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003789 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003790 }
chaviw291d88a2019-02-14 10:33:58 -08003791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792}
3793
3794void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003795 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003796 if (DEBUG_FOCUS) {
3797 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3798 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003801 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802
Tiger Huang721e26f2018-07-24 22:26:19 +08003803 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3804 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003805
3806 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3807 inputApplicationHandle != oldFocusedApplicationHandle) {
3808 resetNoFocusedWindowTimeoutLocked();
3809 }
3810
Yi Kong9b14ac62018-07-17 13:48:38 -07003811 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003812 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003813 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003815 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003816 oldFocusedApplicationHandle.clear();
3817 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 } // release lock
3820
3821 // Wake up poll loop since it may need to make new input dispatching choices.
3822 mLooper->wake();
3823}
3824
Tiger Huang721e26f2018-07-24 22:26:19 +08003825/**
3826 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3827 * the display not specified.
3828 *
3829 * We track any unreleased events for each window. If a window loses the ability to receive the
3830 * released event, we will send a cancel event to it. So when the focused display is changed, we
3831 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3832 * display. The display-specified events won't be affected.
3833 */
3834void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003835 if (DEBUG_FOCUS) {
3836 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3837 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003838 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003839 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003840
3841 if (mFocusedDisplayId != displayId) {
3842 sp<InputWindowHandle> oldFocusedWindowHandle =
3843 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3844 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003845 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003846 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003847 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 CancelationOptions
3849 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3850 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003851 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003852 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3853 }
3854 }
3855 mFocusedDisplayId = displayId;
3856
3857 // Sanity check
3858 sp<InputWindowHandle> newFocusedWindowHandle =
3859 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003860 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003861
Tiger Huang721e26f2018-07-24 22:26:19 +08003862 if (newFocusedWindowHandle == nullptr) {
3863 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3864 if (!mFocusedWindowHandlesByDisplay.empty()) {
3865 ALOGE("But another display has a focused window:");
3866 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003867 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003868 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003870 }
3871 }
3872 }
3873 }
3874
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003875 if (DEBUG_FOCUS) {
3876 logDispatchStateLocked();
3877 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003878 } // release lock
3879
3880 // Wake up poll loop since it may need to make new input dispatching choices.
3881 mLooper->wake();
3882}
3883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003885 if (DEBUG_FOCUS) {
3886 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
3889 bool changed;
3890 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
3893 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3894 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003895 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
3897
3898 if (mDispatchEnabled && !enabled) {
3899 resetAndDropEverythingLocked("dispatcher is being disabled");
3900 }
3901
3902 mDispatchEnabled = enabled;
3903 mDispatchFrozen = frozen;
3904 changed = true;
3905 } else {
3906 changed = false;
3907 }
3908
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003909 if (DEBUG_FOCUS) {
3910 logDispatchStateLocked();
3911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 } // release lock
3913
3914 if (changed) {
3915 // Wake up poll loop since it may need to make new input dispatching choices.
3916 mLooper->wake();
3917 }
3918}
3919
3920void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003921 if (DEBUG_FOCUS) {
3922 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
3925 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003926 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
3928 if (mInputFilterEnabled == enabled) {
3929 return;
3930 }
3931
3932 mInputFilterEnabled = enabled;
3933 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3934 } // release lock
3935
3936 // Wake up poll loop since there might be work to do to drop everything.
3937 mLooper->wake();
3938}
3939
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003940void InputDispatcher::setInTouchMode(bool inTouchMode) {
3941 std::scoped_lock lock(mLock);
3942 mInTouchMode = inTouchMode;
3943}
3944
chaviwfbe5d9c2018-12-26 12:23:37 -08003945bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3946 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003947 if (DEBUG_FOCUS) {
3948 ALOGD("Trivial transfer to same window.");
3949 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003950 return true;
3951 }
3952
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
chaviwfbe5d9c2018-12-26 12:23:37 -08003956 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3957 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003958 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003959 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 return false;
3961 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003962 if (DEBUG_FOCUS) {
3963 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3964 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003967 if (DEBUG_FOCUS) {
3968 ALOGD("Cannot transfer focus because windows are on different displays.");
3969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 return false;
3971 }
3972
3973 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003974 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3975 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003976 for (size_t i = 0; i < state.windows.size(); i++) {
3977 const TouchedWindow& touchedWindow = state.windows[i];
3978 if (touchedWindow.windowHandle == fromWindowHandle) {
3979 int32_t oldTargetFlags = touchedWindow.targetFlags;
3980 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003982 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003984 int32_t newTargetFlags = oldTargetFlags &
3985 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3986 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003987 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Jeff Brownf086ddb2014-02-11 14:28:48 -08003989 found = true;
3990 goto Found;
3991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003994 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003996 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003997 if (DEBUG_FOCUS) {
3998 ALOGD("Focus transfer failed because from window did not have focus.");
3999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 return false;
4001 }
4002
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004003 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4004 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004005 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004006 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007 CancelationOptions
4008 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4009 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004011 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004014 if (DEBUG_FOCUS) {
4015 logDispatchStateLocked();
4016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 } // release lock
4018
4019 // Wake up poll loop since it may need to make new input dispatching choices.
4020 mLooper->wake();
4021 return true;
4022}
4023
4024void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004025 if (DEBUG_FOCUS) {
4026 ALOGD("Resetting and dropping all events (%s).", reason);
4027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028
4029 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4030 synthesizeCancelationEventsForAllConnectionsLocked(options);
4031
4032 resetKeyRepeatLocked();
4033 releasePendingEventLocked();
4034 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004035 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004037 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004038 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004040 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041}
4042
4043void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004044 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 dumpDispatchStateLocked(dump);
4046
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004047 std::istringstream stream(dump);
4048 std::string line;
4049
4050 while (std::getline(stream, line, '\n')) {
4051 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
4053}
4054
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004055void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004056 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4057 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4058 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004059 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060
Tiger Huang721e26f2018-07-24 22:26:19 +08004061 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4062 dump += StringPrintf(INDENT "FocusedApplications:\n");
4063 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4064 const int32_t displayId = it.first;
4065 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004067 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004069 ns2ms(applicationHandle
4070 ->getDispatchingTimeout(
4071 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4072 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004075 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004077
4078 if (!mFocusedWindowHandlesByDisplay.empty()) {
4079 dump += StringPrintf(INDENT "FocusedWindows:\n");
4080 for (auto& it : mFocusedWindowHandlesByDisplay) {
4081 const int32_t displayId = it.first;
4082 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4084 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004085 }
4086 } else {
4087 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004090 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004091 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004092 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4093 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004094 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 state.displayId, toString(state.down), toString(state.split),
4096 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004097 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004098 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004099 for (size_t i = 0; i < state.windows.size(); i++) {
4100 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004101 dump += StringPrintf(INDENT4
4102 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4103 i, touchedWindow.windowHandle->getName().c_str(),
4104 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004105 }
4106 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004107 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004108 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004109 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004110 dump += INDENT3 "Portal windows:\n";
4111 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004112 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4114 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004115 }
4116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 }
4118 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
4121
Arthur Hungb92218b2018-08-14 12:00:21 +08004122 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004124 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004125 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004126 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004127 dump += INDENT2 "Windows:\n";
4128 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004129 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004134 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4135 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004137 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 i, windowInfo->name.c_str(), windowInfo->displayId,
4139 windowInfo->portalToDisplayId,
4140 toString(windowInfo->paused),
4141 toString(windowInfo->hasFocus),
4142 toString(windowInfo->hasWallpaper),
4143 toString(windowInfo->visible),
4144 toString(windowInfo->canReceiveKeys),
4145 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004146 windowInfo->layoutParamsType, windowInfo->frameLeft,
4147 windowInfo->frameTop, windowInfo->frameRight,
4148 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4149 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004150 dumpRegion(dump, windowInfo->touchableRegion);
4151 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004152 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4153 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004155 ns2ms(windowInfo->dispatchingTimeout));
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004156 dump += StringPrintf(INDENT4 " flags: %s\n",
4157 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4158 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004159 }
4160 } else {
4161 dump += INDENT2 "Windows: <none>\n";
4162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
4164 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004165 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167
Michael Wright3dd60e22019-03-27 22:06:44 +00004168 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004169 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004170 const std::vector<Monitor>& monitors = it.second;
4171 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4172 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 }
4174 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004175 const std::vector<Monitor>& monitors = it.second;
4176 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4177 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004180 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 }
4182
4183 nsecs_t currentTime = now();
4184
4185 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004186 if (!mRecentQueue.empty()) {
4187 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4188 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004191 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 }
4196
4197 // Dump event currently being dispatched.
4198 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += INDENT "PendingEvent:\n";
4200 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004202 dump += StringPrintf(", age=%" PRId64 "ms\n",
4203 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 }
4207
4208 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004209 if (!mInboundQueue.empty()) {
4210 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4211 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004214 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 }
4216 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004217 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 }
4219
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004220 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004222 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4223 const KeyReplacement& replacement = pair.first;
4224 int32_t newKeyCode = pair.second;
4225 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004227 }
4228 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004230 }
4231
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004232 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004234 for (const auto& pair : mConnectionsByFd) {
4235 const sp<Connection>& connection = pair.second;
4236 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004237 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004238 pair.first, connection->getInputChannelName().c_str(),
4239 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004240 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004242 if (!connection->outboundQueue.empty()) {
4243 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4244 connection->outboundQueue.size());
4245 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 dump.append(INDENT4);
4247 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004248 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4249 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004251 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004257 if (!connection->waitQueue.empty()) {
4258 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4259 connection->waitQueue.size());
4260 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004263 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004264 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004266 ns2ms(currentTime - entry->eventEntry->eventTime),
4267 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004270 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 }
4272 }
4273 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
4277 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004278 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4279 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004281 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004285 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4286 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4287 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288}
4289
Michael Wright3dd60e22019-03-27 22:06:44 +00004290void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4291 const size_t numMonitors = monitors.size();
4292 for (size_t i = 0; i < numMonitors; i++) {
4293 const Monitor& monitor = monitors[i];
4294 const sp<InputChannel>& channel = monitor.inputChannel;
4295 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4296 dump += "\n";
4297 }
4298}
4299
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004300status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004302 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303#endif
4304
4305 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004306 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004307 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004308 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 return BAD_VALUE;
4312 }
4313
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004314 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
4316 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004317 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004318 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4321 } // release lock
4322
4323 // Wake the looper because some connections have changed.
4324 mLooper->wake();
4325 return OK;
4326}
4327
Michael Wright3dd60e22019-03-27 22:06:44 +00004328status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004330 { // acquire lock
4331 std::scoped_lock _l(mLock);
4332
4333 if (displayId < 0) {
4334 ALOGW("Attempted to register input monitor without a specified display.");
4335 return BAD_VALUE;
4336 }
4337
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004338 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004339 ALOGW("Attempted to register input monitor without an identifying token.");
4340 return BAD_VALUE;
4341 }
4342
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004343 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004344
4345 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004346 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004347 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004349 auto& monitorsByDisplay =
4350 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004351 monitorsByDisplay[displayId].emplace_back(inputChannel);
4352
4353 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004354 }
4355 // Wake the looper because some connections have changed.
4356 mLooper->wake();
4357 return OK;
4358}
4359
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4361#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004362 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363#endif
4364
4365 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004366 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
4368 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4369 if (status) {
4370 return status;
4371 }
4372 } // release lock
4373
4374 // Wake the poll loop because removing the connection may have changed the current
4375 // synchronization state.
4376 mLooper->wake();
4377 return OK;
4378}
4379
4380status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004382 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004383 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 return BAD_VALUE;
4387 }
4388
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004390 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004391
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 if (connection->monitor) {
4393 removeMonitorChannelLocked(inputChannel);
4394 }
4395
4396 mLooper->removeFd(inputChannel->getFd());
4397
4398 nsecs_t currentTime = now();
4399 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4400
4401 connection->status = Connection::STATUS_ZOMBIE;
4402 return OK;
4403}
4404
4405void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004406 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4407 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4408}
4409
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410void InputDispatcher::removeMonitorChannelLocked(
4411 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004412 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004414 std::vector<Monitor>& monitors = it->second;
4415 const size_t numMonitors = monitors.size();
4416 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 if (monitors[i].inputChannel == inputChannel) {
4418 monitors.erase(monitors.begin() + i);
4419 break;
4420 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004421 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004422 if (monitors.empty()) {
4423 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004424 } else {
4425 ++it;
4426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 }
4428}
4429
Michael Wright3dd60e22019-03-27 22:06:44 +00004430status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4431 { // acquire lock
4432 std::scoped_lock _l(mLock);
4433 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4434
4435 if (!foundDisplayId) {
4436 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4437 return BAD_VALUE;
4438 }
4439 int32_t displayId = foundDisplayId.value();
4440
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004441 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4442 mTouchStatesByDisplay.find(displayId);
4443 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4445 return BAD_VALUE;
4446 }
4447
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004448 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004449 std::optional<int32_t> foundDeviceId;
4450 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004451 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 foundDeviceId = state.deviceId;
4453 }
4454 }
4455 if (!foundDeviceId || !state.down) {
4456 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004457 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004458 return BAD_VALUE;
4459 }
4460 int32_t deviceId = foundDeviceId.value();
4461
4462 // Send cancel events to all the input channels we're stealing from.
4463 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004465 options.deviceId = deviceId;
4466 options.displayId = displayId;
4467 for (const TouchedWindow& window : state.windows) {
4468 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004469 if (channel != nullptr) {
4470 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4471 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004472 }
4473 // Then clear the current touch state so we stop dispatching to them as well.
4474 state.filterNonMonitors();
4475 }
4476 return OK;
4477}
4478
Michael Wright3dd60e22019-03-27 22:06:44 +00004479std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4480 const sp<IBinder>& token) {
4481 for (const auto& it : mGestureMonitorsByDisplay) {
4482 const std::vector<Monitor>& monitors = it.second;
4483 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004484 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004485 return it.first;
4486 }
4487 }
4488 }
4489 return std::nullopt;
4490}
4491
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004492sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004493 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004494 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004495 }
4496
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004497 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004498 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004499 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004500 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
4502 }
Robert Carr4e670e52018-08-15 13:26:12 -07004503
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004504 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505}
4506
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004507void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004508 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004509 removeByValue(mConnectionsByFd, connection);
4510}
4511
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004512void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4513 const sp<Connection>& connection, uint32_t seq,
4514 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004515 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4516 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 commandEntry->connection = connection;
4518 commandEntry->eventTime = currentTime;
4519 commandEntry->seq = seq;
4520 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004521 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522}
4523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004524void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4525 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004529 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4530 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004532 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533}
4534
chaviw0c06c6e2019-01-09 13:27:07 -08004535void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004536 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004537 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4538 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004539 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4540 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004541 commandEntry->oldToken = oldToken;
4542 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004543 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004544}
4545
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4547 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4548 // is already healthy again. Don't raise ANR in this situation
4549 if (connection->waitQueue.empty()) {
4550 ALOGI("Not raising ANR because the connection %s has recovered",
4551 connection->inputChannel->getName().c_str());
4552 return;
4553 }
4554 /**
4555 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4556 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4557 * has changed. This could cause newer entries to time out before the already dispatched
4558 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4559 * processes the events linearly. So providing information about the oldest entry seems to be
4560 * most useful.
4561 */
4562 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4563 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4564 std::string reason =
4565 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4566 connection->inputChannel->getName().c_str(),
4567 ns2ms(currentWait),
4568 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004570 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4571 reason);
4572
4573 std::unique_ptr<CommandEntry> commandEntry =
4574 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4575 commandEntry->inputApplicationHandle = nullptr;
4576 commandEntry->inputChannel = connection->inputChannel;
4577 commandEntry->reason = std::move(reason);
4578 postCommandLocked(std::move(commandEntry));
4579}
4580
4581void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4582 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4583 application->getName().c_str());
4584
4585 updateLastAnrStateLocked(application, reason);
4586
4587 std::unique_ptr<CommandEntry> commandEntry =
4588 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4589 commandEntry->inputApplicationHandle = application;
4590 commandEntry->inputChannel = nullptr;
4591 commandEntry->reason = std::move(reason);
4592 postCommandLocked(std::move(commandEntry));
4593}
4594
4595void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4596 const std::string& reason) {
4597 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4598 updateLastAnrStateLocked(windowLabel, reason);
4599}
4600
4601void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4602 const std::string& reason) {
4603 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4604 updateLastAnrStateLocked(windowLabel, reason);
4605}
4606
4607void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4608 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004610 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 struct tm tm;
4612 localtime_r(&t, &tm);
4613 char timestr[64];
4614 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004615 mLastAnrState.clear();
4616 mLastAnrState += INDENT "ANR:\n";
4617 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4619 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004620 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621}
4622
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004623void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 mLock.unlock();
4625
4626 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4627
4628 mLock.lock();
4629}
4630
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 sp<Connection> connection = commandEntry->connection;
4633
4634 if (connection->status != Connection::STATUS_ZOMBIE) {
4635 mLock.unlock();
4636
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004637 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638
4639 mLock.lock();
4640 }
4641}
4642
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004643void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004644 sp<IBinder> oldToken = commandEntry->oldToken;
4645 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004646 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004647 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004648 mLock.lock();
4649}
4650
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004651void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004652 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004653 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 mLock.unlock();
4655
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004656 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004657 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658
4659 mLock.lock();
4660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661 if (timeoutExtension > 0) {
4662 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4663 } else {
4664 // stop waking up for events in this connection, it is already not responding
4665 sp<Connection> connection = getConnectionLocked(token);
4666 if (connection == nullptr) {
4667 return;
4668 }
4669 cancelEventsForAnrLocked(connection);
4670 }
4671}
4672
4673void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4674 const sp<IBinder>& connectionToken,
4675 nsecs_t timeoutExtension) {
4676 sp<Connection> connection = getConnectionLocked(connectionToken);
4677 if (connection == nullptr) {
4678 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4679 // Maybe ANR happened because there's no focused window?
4680 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4681 mAwaitedFocusedApplication = application;
4682 } else {
4683 // It's also possible that the connection already disappeared. No action necessary.
4684 }
4685 return;
4686 }
4687
4688 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4689 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4690
4691 connection->responsive = true;
4692 const nsecs_t newTimeout = now() + timeoutExtension;
4693 for (DispatchEntry* entry : connection->waitQueue) {
4694 if (newTimeout >= entry->timeoutTime) {
4695 // Already removed old entries when connection was marked unresponsive
4696 entry->timeoutTime = newTimeout;
4697 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4698 }
4699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700}
4701
4702void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4703 CommandEntry* commandEntry) {
4704 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004705 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
4707 mLock.unlock();
4708
Michael Wright2b3c3302018-03-02 17:19:13 +00004709 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004711 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004712 : nullptr;
4713 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004714 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4715 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718
4719 mLock.lock();
4720
4721 if (delay < 0) {
4722 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4723 } else if (!delay) {
4724 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4725 } else {
4726 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4727 entry->interceptKeyWakeupTime = now() + delay;
4728 }
4729 entry->release();
4730}
4731
chaviwfd6d3512019-03-25 13:23:49 -07004732void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4733 mLock.unlock();
4734 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4735 mLock.lock();
4736}
4737
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738/**
4739 * Connection is responsive if it has no events in the waitQueue that are older than the
4740 * current time.
4741 */
4742static bool isConnectionResponsive(const Connection& connection) {
4743 const nsecs_t currentTime = now();
4744 for (const DispatchEntry* entry : connection.waitQueue) {
4745 if (entry->timeoutTime < currentTime) {
4746 return false;
4747 }
4748 }
4749 return true;
4750}
4751
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004754 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004756 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
4758 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004759 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004760 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004761 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004763 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004764 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004765 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004766 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4767 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004768 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004769 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004770
4771 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004772 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004773 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4774 restartEvent =
4775 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004776 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004777 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4778 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4779 handled);
4780 } else {
4781 restartEvent = false;
4782 }
4783
4784 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004785 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004786 // contents of the wait queue to have been drained, so we need to double-check
4787 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004788 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4789 if (dispatchEntryIt != connection->waitQueue.end()) {
4790 dispatchEntry = *dispatchEntryIt;
4791 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 mAnrTracker.erase(dispatchEntry->timeoutTime,
4793 connection->inputChannel->getConnectionToken());
4794 if (!connection->responsive) {
4795 connection->responsive = isConnectionResponsive(*connection);
4796 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004797 traceWaitQueueLength(connection);
4798 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004799 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004800 traceOutboundQueueLength(connection);
4801 } else {
4802 releaseDispatchEntry(dispatchEntry);
4803 }
4804 }
4805
4806 // Start the next dispatch cycle for this connection.
4807 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808}
4809
4810bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004811 DispatchEntry* dispatchEntry,
4812 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004813 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004814 if (!handled) {
4815 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004816 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004817 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004818 return false;
4819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004821 // Get the fallback key state.
4822 // Clear it out after dispatching the UP.
4823 int32_t originalKeyCode = keyEntry->keyCode;
4824 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4825 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4826 connection->inputState.removeFallbackKey(originalKeyCode);
4827 }
4828
4829 if (handled || !dispatchEntry->hasForegroundTarget()) {
4830 // If the application handles the original key for which we previously
4831 // generated a fallback or if the window is not a foreground window,
4832 // then cancel the associated fallback key, if any.
4833 if (fallbackKeyCode != -1) {
4834 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004837 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4838 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4839 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004841 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004842 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843
4844 mLock.unlock();
4845
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004846 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
4849 mLock.lock();
4850
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004851 // Cancel the fallback key.
4852 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004854 "application handled the original non-fallback key "
4855 "or is no longer a foreground target, "
4856 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 options.keyCode = fallbackKeyCode;
4858 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004860 connection->inputState.removeFallbackKey(originalKeyCode);
4861 }
4862 } else {
4863 // If the application did not handle a non-fallback key, first check
4864 // that we are in a good state to perform unhandled key event processing
4865 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004867 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004869 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004870 "since this is not an initial down. "
4871 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4872 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004874 return false;
4875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004877 // Dispatch the unhandled key to the policy.
4878#if DEBUG_OUTBOUND_EVENT_DETAILS
4879 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004880 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4881 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004882#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004883 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884
4885 mLock.unlock();
4886
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004887 bool fallback =
4888 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4889 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004890
4891 mLock.lock();
4892
4893 if (connection->status != Connection::STATUS_NORMAL) {
4894 connection->inputState.removeFallbackKey(originalKeyCode);
4895 return false;
4896 }
4897
4898 // Latch the fallback keycode for this key on an initial down.
4899 // The fallback keycode cannot change at any other point in the lifecycle.
4900 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004902 fallbackKeyCode = event.getKeyCode();
4903 } else {
4904 fallbackKeyCode = AKEYCODE_UNKNOWN;
4905 }
4906 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4907 }
4908
4909 ALOG_ASSERT(fallbackKeyCode != -1);
4910
4911 // Cancel the fallback key if the policy decides not to send it anymore.
4912 // We will continue to dispatch the key to the policy but we will no
4913 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004914 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4915 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916#if DEBUG_OUTBOUND_EVENT_DETAILS
4917 if (fallback) {
4918 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004919 "as a fallback for %d, but on the DOWN it had requested "
4920 "to send %d instead. Fallback canceled.",
4921 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004922 } else {
4923 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004924 "but on the DOWN it had requested to send %d. "
4925 "Fallback canceled.",
4926 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004927 }
4928#endif
4929
4930 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4931 "canceling fallback, policy no longer desires it");
4932 options.keyCode = fallbackKeyCode;
4933 synthesizeCancelationEventsForConnectionLocked(connection, options);
4934
4935 fallback = false;
4936 fallbackKeyCode = AKEYCODE_UNKNOWN;
4937 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004938 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004939 }
4940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
4942#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004943 {
4944 std::string msg;
4945 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4946 connection->inputState.getFallbackKeys();
4947 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004948 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004950 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 }
4953#endif
4954
4955 if (fallback) {
4956 // Restart the dispatch cycle using the fallback key.
4957 keyEntry->eventTime = event.getEventTime();
4958 keyEntry->deviceId = event.getDeviceId();
4959 keyEntry->source = event.getSource();
4960 keyEntry->displayId = event.getDisplayId();
4961 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4962 keyEntry->keyCode = fallbackKeyCode;
4963 keyEntry->scanCode = event.getScanCode();
4964 keyEntry->metaState = event.getMetaState();
4965 keyEntry->repeatCount = event.getRepeatCount();
4966 keyEntry->downTime = event.getDownTime();
4967 keyEntry->syntheticRepeat = false;
4968
4969#if DEBUG_OUTBOUND_EVENT_DETAILS
4970 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004971 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4972 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004973#endif
4974 return true; // restart the event
4975 } else {
4976#if DEBUG_OUTBOUND_EVENT_DETAILS
4977 ALOGD("Unhandled key event: No fallback key.");
4978#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004979
4980 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004981 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
4983 }
4984 return false;
4985}
4986
4987bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004988 DispatchEntry* dispatchEntry,
4989 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 return false;
4991}
4992
4993void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4994 mLock.unlock();
4995
4996 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4997
4998 mLock.lock();
4999}
5000
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005001KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5002 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005003 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005004 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5005 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005006 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007}
5008
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005009void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5010 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 // TODO Write some statistics about how long we spend waiting.
5012}
5013
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005014/**
5015 * Report the touch event latency to the statsd server.
5016 * Input events are reported for statistics if:
5017 * - This is a touchscreen event
5018 * - InputFilter is not enabled
5019 * - Event is not injected or synthesized
5020 *
5021 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5022 * from getting aggregated with the "old" data.
5023 */
5024void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5025 REQUIRES(mLock) {
5026 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5027 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5028 if (!reportForStatistics) {
5029 return;
5030 }
5031
5032 if (mTouchStatistics.shouldReport()) {
5033 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5034 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5035 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5036 mTouchStatistics.reset();
5037 }
5038 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5039 mTouchStatistics.addValue(latencyMicros);
5040}
5041
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042void InputDispatcher::traceInboundQueueLengthLocked() {
5043 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005044 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 }
5046}
5047
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005048void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 if (ATRACE_ENABLED()) {
5050 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005051 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005052 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 }
5054}
5055
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005056void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 if (ATRACE_ENABLED()) {
5058 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005059 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005060 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062}
5063
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005064void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005067 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 dumpDispatchStateLocked(dump);
5069
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005070 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005072 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 }
5074}
5075
5076void InputDispatcher::monitor() {
5077 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005078 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005080 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081}
5082
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005083/**
5084 * Wake up the dispatcher and wait until it processes all events and commands.
5085 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5086 * this method can be safely called from any thread, as long as you've ensured that
5087 * the work you are interested in completing has already been queued.
5088 */
5089bool InputDispatcher::waitForIdle() {
5090 /**
5091 * Timeout should represent the longest possible time that a device might spend processing
5092 * events and commands.
5093 */
5094 constexpr std::chrono::duration TIMEOUT = 100ms;
5095 std::unique_lock lock(mLock);
5096 mLooper->wake();
5097 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5098 return result == std::cv_status::no_timeout;
5099}
5100
Garfield Tane84e6f92019-08-29 17:28:41 -07005101} // namespace android::inputdispatcher