blob: 36bbc6dd178bce8b61198f50d32e97a569423258 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070050#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080051#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010052#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070053#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050054#include <openssl/hmac.h>
55#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070082constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for all pending events to be processed when an app switch
85// key is on the way. This is used to preempt input dispatch and drop input events
86// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for an event to be dispatched (measured since its eventTime)
90// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// 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 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070099// Additional key latency in case a connection is still processing some motion events.
100// This will help with the case when a user touched a button that opens a new window,
101// and gives us the chance to dispatch the key to this new window.
102constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500163static int64_t millis(std::chrono::nanoseconds t) {
164 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
165}
166
Michael Wright7b159c92015-05-14 14:48:03 +0100167static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 const PointerProperties* pointerProperties) {
169 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 ALOGE("Motion event has invalid action code 0x%x", action);
171 return false;
172 }
173 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000174 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 return false;
177 }
178 BitSet32 pointerIdBits;
179 for (size_t i = 0; i < pointerCount; i++) {
180 int32_t id = pointerProperties[i].id;
181 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
183 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return false;
185 }
186 if (pointerIdBits.hasBit(id)) {
187 ALOGE("Motion event has duplicate pointer id %d", id);
188 return false;
189 }
190 pointerIdBits.markBit(id);
191 }
192 return true;
193}
194
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800195static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800197 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return;
199 }
200
201 bool first = true;
202 Region::const_iterator cur = region.begin();
203 Region::const_iterator const tail = region.end();
204 while (cur != tail) {
205 if (first) {
206 first = false;
207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800208 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800210 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 cur++;
212 }
213}
214
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700215/**
216 * Find the entry in std::unordered_map by key, and return it.
217 * If the entry is not found, return a default constructed entry.
218 *
219 * Useful when the entries are vectors, since an empty vector will be returned
220 * if the entry is not found.
221 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
222 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700223template <typename K, typename V>
224static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700225 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700226 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800227}
228
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700229/**
230 * Find the entry in std::unordered_map by value, and remove it.
231 * If more than one entry has the same value, then all matching
232 * key-value pairs will be removed.
233 *
234 * Return true if at least one value has been removed.
235 */
236template <typename K, typename V>
237static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
238 bool removed = false;
239 for (auto it = map.begin(); it != map.end();) {
240 if (it->second == value) {
241 it = map.erase(it);
242 removed = true;
243 } else {
244 it++;
245 }
246 }
247 return removed;
248}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249
chaviwaf87b3e2019-10-01 16:59:28 -0700250static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
251 if (first == second) {
252 return true;
253 }
254
255 if (first == nullptr || second == nullptr) {
256 return false;
257 }
258
259 return first->getToken() == second->getToken();
260}
261
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800262static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
263 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
264}
265
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000266static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
267 EventEntry* eventEntry,
268 int32_t inputTargetFlags) {
269 if (inputTarget.useDefaultPointerInfo()) {
270 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
271 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
272 inputTargetFlags, pointerInfo.xOffset,
273 pointerInfo.yOffset, inputTarget.globalScaleFactor,
274 pointerInfo.windowXScale, pointerInfo.windowYScale);
275 }
276
277 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
278 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
279
280 PointerCoords pointerCoords[motionEntry.pointerCount];
281
282 // Use the first pointer information to normalize all other pointers. This could be any pointer
283 // as long as all other pointers are normalized to the same value and the final DispatchEntry
284 // uses the offset and scale for the normalized pointer.
285 const PointerInfo& firstPointerInfo =
286 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
287
288 // Iterate through all pointers in the event to normalize against the first.
289 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
290 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
291 uint32_t pointerId = uint32_t(pointerProperties.id);
292 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
293
294 // The scale factor is the ratio of the current pointers scale to the normalized scale.
295 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
296 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
297
298 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
299 // First apply the current pointers offset to set the window at 0,0
300 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
301 // Next scale the coordinates.
302 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
303 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
304 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
305 -firstPointerInfo.yOffset);
306 }
307
308 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800309 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
311 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
312 motionEntry.metaState, motionEntry.buttonState,
313 motionEntry.classification, motionEntry.edgeFlags,
314 motionEntry.xPrecision, motionEntry.yPrecision,
315 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
316 motionEntry.downTime, motionEntry.pointerCount,
317 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
318 0 /* yOffset */);
319
320 if (motionEntry.injectionState) {
321 combinedMotionEntry->injectionState = motionEntry.injectionState;
322 combinedMotionEntry->injectionState->refCount += 1;
323 }
324
325 std::unique_ptr<DispatchEntry> dispatchEntry =
326 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
327 inputTargetFlags, firstPointerInfo.xOffset,
328 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
329 firstPointerInfo.windowXScale,
330 firstPointerInfo.windowYScale);
331 combinedMotionEntry->release();
332 return dispatchEntry;
333}
334
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700335static void addGestureMonitors(const std::vector<Monitor>& monitors,
336 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
337 float yOffset = 0) {
338 if (monitors.empty()) {
339 return;
340 }
341 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
342 for (const Monitor& monitor : monitors) {
343 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
344 }
345}
346
Gang Wang342c9272020-01-13 13:15:04 -0500347static std::array<uint8_t, 128> getRandomKey() {
348 std::array<uint8_t, 128> key;
349 if (RAND_bytes(key.data(), key.size()) != 1) {
350 LOG_ALWAYS_FATAL("Can't generate HMAC key");
351 }
352 return key;
353}
354
355// --- HmacKeyManager ---
356
357HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
358
359std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
360 size_t size;
361 switch (event.type) {
362 case VerifiedInputEvent::Type::KEY: {
363 size = sizeof(VerifiedKeyEvent);
364 break;
365 }
366 case VerifiedInputEvent::Type::MOTION: {
367 size = sizeof(VerifiedMotionEvent);
368 break;
369 }
370 }
Gang Wang342c9272020-01-13 13:15:04 -0500371 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700372 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500373}
374
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700375std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500376 // SHA256 always generates 32-bytes result
377 std::array<uint8_t, 32> hash;
378 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700379 uint8_t* result =
380 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500381 if (result == nullptr) {
382 ALOGE("Could not sign the data using HMAC");
383 return INVALID_HMAC;
384 }
385
386 if (hashLen != hash.size()) {
387 ALOGE("HMAC-SHA256 has unexpected length");
388 return INVALID_HMAC;
389 }
390
391 return hash;
392}
393
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394// --- InputDispatcher ---
395
Garfield Tan00f511d2019-06-12 16:55:40 -0700396InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
397 : mPolicy(policy),
398 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700399 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800400 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700401 mAppSwitchSawKeyDown(false),
402 mAppSwitchDueTime(LONG_LONG_MAX),
403 mNextUnblockedEvent(nullptr),
404 mDispatchEnabled(false),
405 mDispatchFrozen(false),
406 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800407 // mInTouchMode will be initialized by the WindowManager to the default device config.
408 // To avoid leaking stack in case that call never comes, and for tests,
409 // initialize it here anyways.
410 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700411 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800413 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
Yi Kong9b14ac62018-07-17 13:48:38 -0700415 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416
417 policy->getDispatcherConfiguration(&mConfig);
418}
419
420InputDispatcher::~InputDispatcher() {
421 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800422 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800423
424 resetKeyRepeatLocked();
425 releasePendingEventLocked();
426 drainInboundQueueLocked();
427 }
428
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700429 while (!mConnectionsByFd.empty()) {
430 sp<Connection> connection = mConnectionsByFd.begin()->second;
431 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 }
433}
434
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700435status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437 return ALREADY_EXISTS;
438 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700439 mThread = std::make_unique<InputThread>(
440 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
441 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442}
443
444status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700445 if (mThread && mThread->isCallingThread()) {
446 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700447 return INVALID_OPERATION;
448 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700449 mThread.reset();
450 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700451}
452
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453void InputDispatcher::dispatchOnce() {
454 nsecs_t nextWakeupTime = LONG_LONG_MAX;
455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800456 std::scoped_lock _l(mLock);
457 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458
459 // Run a dispatch loop if there are no pending commands.
460 // The dispatch loop might enqueue commands to run afterwards.
461 if (!haveCommandsLocked()) {
462 dispatchOnceInnerLocked(&nextWakeupTime);
463 }
464
465 // Run all pending commands if there are any.
466 // If any commands were run then force the next poll to wake up immediately.
467 if (runCommandsLockedInterruptible()) {
468 nextWakeupTime = LONG_LONG_MIN;
469 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700471 // If we are still waiting for ack on some events,
472 // we might have to wake up earlier to check if an app is anr'ing.
473 const nsecs_t nextAnrCheck = processAnrsLocked();
474 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
475
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800476 // We are about to enter an infinitely long sleep, because we have no commands or
477 // pending or queued events
478 if (nextWakeupTime == LONG_LONG_MAX) {
479 mDispatcherEnteredIdle.notify_all();
480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 } // release lock
482
483 // Wait for callback or timeout or wake. (make sure we round up, not down)
484 nsecs_t currentTime = now();
485 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
486 mLooper->pollOnce(timeoutMillis);
487}
488
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700489/**
490 * Check if any of the connections' wait queues have events that are too old.
491 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
492 * Return the time at which we should wake up next.
493 */
494nsecs_t InputDispatcher::processAnrsLocked() {
495 const nsecs_t currentTime = now();
496 nsecs_t nextAnrCheck = LONG_LONG_MAX;
497 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
498 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
499 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
500 onAnrLocked(mAwaitedFocusedApplication);
501 mAwaitedFocusedApplication.clear();
502 return LONG_LONG_MIN;
503 } else {
504 // Keep waiting
505 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
506 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
507 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
508 }
509 }
510
511 // Check if any connection ANRs are due
512 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
513 if (currentTime < nextAnrCheck) { // most likely scenario
514 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
515 }
516
517 // If we reached here, we have an unresponsive connection.
518 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
519 if (connection == nullptr) {
520 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
521 return nextAnrCheck;
522 }
523 connection->responsive = false;
524 // Stop waking up for this unresponsive connection
525 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
526 onAnrLocked(connection);
527 return LONG_LONG_MIN;
528}
529
530nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
531 sp<InputWindowHandle> window = getWindowHandleLocked(token);
532 if (window != nullptr) {
533 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
534 }
535 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
536}
537
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
539 nsecs_t currentTime = now();
540
Jeff Browndc5992e2014-04-11 01:27:26 -0700541 // Reset the key repeat timer whenever normal dispatch is suspended while the
542 // device is in a non-interactive state. This is to ensure that we abort a key
543 // repeat if the device is just coming out of sleep.
544 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 resetKeyRepeatLocked();
546 }
547
548 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
549 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100550 if (DEBUG_FOCUS) {
551 ALOGD("Dispatch frozen. Waiting some more.");
552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 return;
554 }
555
556 // Optimize latency of app switches.
557 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
558 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
559 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
560 if (mAppSwitchDueTime < *nextWakeupTime) {
561 *nextWakeupTime = mAppSwitchDueTime;
562 }
563
564 // Ready to start a new event.
565 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700567 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 if (isAppSwitchDue) {
569 // The inbound queue is empty so the app switch key we were waiting
570 // for will never arrive. Stop waiting for it.
571 resetPendingAppSwitchLocked(false);
572 isAppSwitchDue = false;
573 }
574
575 // Synthesize a key repeat if appropriate.
576 if (mKeyRepeatState.lastKeyEntry) {
577 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
578 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
579 } else {
580 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
581 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
582 }
583 }
584 }
585
586 // Nothing to do if there is no pending event.
587 if (!mPendingEvent) {
588 return;
589 }
590 } else {
591 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700592 mPendingEvent = mInboundQueue.front();
593 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 traceInboundQueueLengthLocked();
595 }
596
597 // Poke user activity for this event.
598 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700599 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 }
602
603 // Now we have an event to dispatch.
604 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700605 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700607 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700609 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700611 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
613
614 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700615 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 }
617
618 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700619 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 ConfigurationChangedEntry* typedEntry =
621 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
622 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700623 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700624 break;
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700627 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700628 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
629 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 break;
632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100634 case EventEntry::Type::FOCUS: {
635 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
636 dispatchFocusLocked(currentTime, typedEntry);
637 done = true;
638 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
639 break;
640 }
641
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700642 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
644 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700645 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700646 resetPendingAppSwitchLocked(true);
647 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 } else if (dropReason == DropReason::NOT_DROPPED) {
649 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 }
651 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700652 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700655 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
656 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 }
658 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
659 break;
660 }
661
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700662 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700663 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700664 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
665 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700667 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700668 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700670 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
671 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700672 }
673 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
674 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677
678 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700680 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
Michael Wright3a981722015-06-10 15:26:13 +0100682 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683
684 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700685 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 }
687}
688
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700689/**
690 * Return true if the events preceding this incoming motion event should be dropped
691 * Return false otherwise (the default behaviour)
692 */
693bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700695 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700696
697 // Optimize case where the current application is unresponsive and the user
698 // decides to touch a window in a different application.
699 // If the application takes too long to catch up then we drop all events preceding
700 // the touch into the other window.
701 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700702 int32_t displayId = motionEntry.displayId;
703 int32_t x = static_cast<int32_t>(
704 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
705 int32_t y = static_cast<int32_t>(
706 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
707 sp<InputWindowHandle> touchedWindowHandle =
708 findTouchedWindowAtLocked(displayId, x, y, nullptr);
709 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710 touchedWindowHandle->getApplicationToken() !=
711 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700712 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 ALOGI("Pruning input queue because user touched a different application while waiting "
714 "for %s",
715 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700716 return true;
717 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718
719 // Alternatively, maybe there's a gesture monitor that could handle this event
720 std::vector<TouchedMonitor> gestureMonitors =
721 findTouchedGestureMonitorsLocked(displayId, {});
722 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
723 sp<Connection> connection =
724 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000725 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726 // This monitor could take more input. Drop all events preceding this
727 // event, so that gesture monitor could get a chance to receive the stream
728 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
729 "responsive gesture monitor that may handle the event",
730 mAwaitedFocusedApplication->getName().c_str());
731 return true;
732 }
733 }
734 }
735
736 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
737 // yet been processed by some connections, the dispatcher will wait for these motion
738 // events to be processed before dispatching the key event. This is because these motion events
739 // may cause a new window to be launched, which the user might expect to receive focus.
740 // To prevent waiting forever for such events, just send the key to the currently focused window
741 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
742 ALOGD("Received a new pointer down event, stop waiting for events to process and "
743 "just send the pending key event to the focused window.");
744 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700745 }
746 return false;
747}
748
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700750 bool needWake = mInboundQueue.empty();
751 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 traceInboundQueueLengthLocked();
753
754 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700755 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 // Optimize app switch latency.
757 // If the application takes too long to catch up then we drop all events preceding
758 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700759 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700761 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700762 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700768 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 mAppSwitchSawKeyDown = false;
770 needWake = true;
771 }
772 }
773 }
774 break;
775 }
776
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700778 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
779 mNextUnblockedEvent = entry;
780 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100784 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700785 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
786 break;
787 }
788 case EventEntry::Type::CONFIGURATION_CHANGED:
789 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700790 // nothing to do
791 break;
792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
794
795 return needWake;
796}
797
798void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
799 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700800 mRecentQueue.push_back(entry);
801 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
802 mRecentQueue.front()->release();
803 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805}
806
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700808 int32_t y, TouchState* touchState,
809 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700811 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
812 LOG_ALWAYS_FATAL(
813 "Must provide a valid touch state if adding portal windows or outside targets");
814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800816 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
817 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 const InputWindowInfo* windowInfo = windowHandle->getInfo();
819 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100820 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821
822 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100823 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
824 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
825 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800827 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 if (portalToDisplayId != ADISPLAY_ID_NONE &&
829 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 if (addPortalWindows) {
831 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700832 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800833 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 // Found window.
838 return windowHandle;
839 }
840 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841
Michael Wright44753b12020-07-08 13:48:11 +0100842 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700843 touchState->addOrUpdateWindow(windowHandle,
844 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
845 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
849 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700850 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Garfield Tane84e6f92019-08-29 17:28:41 -0700853std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700854 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000855 std::vector<TouchedMonitor> touchedMonitors;
856
857 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
858 addGestureMonitors(monitors, touchedMonitors);
859 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
860 const InputWindowInfo* windowInfo = portalWindow->getInfo();
861 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
863 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000864 }
865 return touchedMonitors;
866}
867
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700868void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 const char* reason;
870 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 reason = "inbound event was dropped because the policy consumed it";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::DISABLED:
878 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 ALOGI("Dropped event because input dispatch is disabled.");
880 }
881 reason = "inbound event was dropped because input dispatch is disabled";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because of pending overdue app switch.");
885 reason = "inbound event was dropped because of pending overdue app switch";
886 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 ALOGI("Dropped event because the current application is not responding and the user "
889 "has started interacting with a different application.");
890 reason = "inbound event was dropped because the current application is not responding "
891 "and the user has started interacting with a different application";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 ALOGI("Dropped event because it is stale.");
895 reason = "inbound event was dropped because it is stale";
896 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::NOT_DROPPED: {
898 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
906 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700909 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
911 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
913 synthesizeCancelationEventsForAllConnectionsLocked(options);
914 } else {
915 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
916 synthesizeCancelationEventsForAllConnectionsLocked(options);
917 }
918 break;
919 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100920 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::CONFIGURATION_CHANGED:
922 case EventEntry::Type::DEVICE_RESET: {
923 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927}
928
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800929static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
931 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932}
933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
935 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
936 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
937 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938}
939
940bool InputDispatcher::isAppSwitchPendingLocked() {
941 return mAppSwitchDueTime != LONG_LONG_MAX;
942}
943
944void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
945 mAppSwitchDueTime = LONG_LONG_MAX;
946
947#if DEBUG_APP_SWITCH
948 if (handled) {
949 ALOGD("App switch has arrived.");
950 } else {
951 ALOGD("App switch was abandoned.");
952 }
953#endif
954}
955
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700961 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 return false;
963 }
964
965 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700966 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700969 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
971 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return true;
974}
975
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
977 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
980void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 while (!mInboundQueue.empty()) {
982 EventEntry* entry = mInboundQueue.front();
983 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 releaseInboundEventLocked(entry);
985 }
986 traceInboundQueueLengthLocked();
987}
988
989void InputDispatcher::releasePendingEventLocked() {
990 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700992 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994}
995
996void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
997 InjectionState* injectionState = entry->injectionState;
998 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
999#if DEBUG_DISPATCH_CYCLE
1000 ALOGD("Injected inbound event was dropped.");
1001#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001002 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007 addRecentEventLocked(entry);
1008 entry->release();
1009}
1010
1011void InputDispatcher::resetKeyRepeatLocked() {
1012 if (mKeyRepeatState.lastKeyEntry) {
1013 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001014 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016}
1017
Garfield Tane84e6f92019-08-29 17:28:41 -07001018KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1020
1021 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001022 uint32_t policyFlags = entry->policyFlags &
1023 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 if (entry->refCount == 1) {
1025 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001026 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 entry->eventTime = currentTime;
1028 entry->policyFlags = policyFlags;
1029 entry->repeatCount += 1;
1030 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001032 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001033 entry->displayId, policyFlags, entry->action, entry->flags,
1034 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
1037 mKeyRepeatState.lastKeyEntry = newEntry;
1038 entry->release();
1039
1040 entry = newEntry;
1041 }
1042 entry->syntheticRepeat = true;
1043
1044 // Increment reference count since we keep a reference to the event in
1045 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1046 entry->refCount += 1;
1047
1048 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1049 return entry;
1050}
1051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1053 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001055 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056#endif
1057
1058 // Reset key repeating in case a keyboard device was added or removed or something.
1059 resetKeyRepeatLocked();
1060
1061 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001062 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1063 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001065 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 return true;
1067}
1068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001071 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073#endif
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 options.deviceId = entry->deviceId;
1077 synthesizeCancelationEventsForAllConnectionsLocked(options);
1078 return true;
1079}
1080
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001081void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001082 if (mPendingEvent != nullptr) {
1083 // Move the pending event to the front of the queue. This will give the chance
1084 // for the pending event to get dispatched to the newly focused window
1085 mInboundQueue.push_front(mPendingEvent);
1086 mPendingEvent = nullptr;
1087 }
1088
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001090 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091
1092 // This event should go to the front of the queue, but behind all other focus events
1093 // Find the last focus event, and insert right after it
1094 std::deque<EventEntry*>::reverse_iterator it =
1095 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1096 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1097
1098 // Maintain the order of focus events. Insert the entry after all other focus events.
1099 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100}
1101
1102void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1103 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1104 if (channel == nullptr) {
1105 return; // Window has gone away
1106 }
1107 InputTarget target;
1108 target.inputChannel = channel;
1109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1110 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 dispatchEventLocked(currentTime, entry, {target});
1113}
1114
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 if (!entry->dispatchInProgress) {
1119 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1120 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1121 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1122 if (mKeyRepeatState.lastKeyEntry &&
1123 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 // We have seen two identical key downs in a row which indicates that the device
1125 // driver is automatically generating key repeats itself. We take note of the
1126 // repeat here, but we disable our own next key repeat timer since it is clear that
1127 // we will not need to synthesize key repeats ourselves.
1128 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1131 } else {
1132 // Not a repeat. Save key down state in case we do see a repeat later.
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1135 }
1136 mKeyRepeatState.lastKeyEntry = entry;
1137 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 resetKeyRepeatLocked();
1140 }
1141
1142 if (entry->repeatCount == 1) {
1143 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1144 } else {
1145 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1146 }
1147
1148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Handle case where the policy asked us to try again later last time.
1154 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1155 if (currentTime < entry->interceptKeyWakeupTime) {
1156 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1157 *nextWakeupTime = entry->interceptKeyWakeupTime;
1158 }
1159 return false; // wait until next wakeup
1160 }
1161 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1162 entry->interceptKeyWakeupTime = 0;
1163 }
1164
1165 // Give the policy a chance to intercept the key.
1166 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1167 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001168 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001169 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001170 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 entry->refCount += 1;
1178 return false; // wait for the command to run
1179 } else {
1180 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1181 }
1182 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001183 if (*dropReason == DropReason::NOT_DROPPED) {
1184 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186 }
1187
1188 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001193 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195 }
1196
1197 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001198 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1202 return false;
1203 }
1204
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001205 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1207 return true;
1208 }
1209
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001210 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
1213 // Dispatch the key.
1214 dispatchEventLocked(currentTime, entry, inputTargets);
1215 return true;
1216}
1217
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001220 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1222 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001223 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1224 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1225 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#endif
1227}
1228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1230 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001231 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 entry->dispatchInProgress = true;
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return true;
1245 }
1246
1247 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1248
1249 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 bool conflictingPointerActions = false;
1253 int32_t injectionResult;
1254 if (isPointerEvent) {
1255 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 } else {
1260 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1265 return false;
1266 }
1267
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001268 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001269 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1270 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1271 return true;
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001274 CancelationOptions::Mode mode(isPointerEvent
1275 ? CancelationOptions::CANCEL_POINTER_EVENTS
1276 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1277 CancelationOptions options(mode, "input event injection failed");
1278 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001285 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001286 std::unordered_map<int32_t, TouchState>::iterator it =
1287 mTouchStatesByDisplay.find(entry->displayId);
1288 if (it != mTouchStatesByDisplay.end()) {
1289 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001291 // The event has gone through these portal windows, so we add monitoring targets of
1292 // the corresponding displays as well.
1293 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001295 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001297 }
1298 }
1299 }
1300 }
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // Dispatch the motion.
1303 if (conflictingPointerActions) {
1304 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 synthesizeCancelationEventsForAllConnectionsLocked(options);
1307 }
1308 dispatchEventLocked(currentTime, entry, inputTargets);
1309 return true;
1310}
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001314 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 ", policyFlags=0x%x, "
1316 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1317 "metaState=0x%x, buttonState=0x%x,"
1318 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1320 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1321 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 "x=%f, y=%f, pressure=%f, size=%f, "
1326 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1327 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001328 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339#endif
1340}
1341
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001342void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1343 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001344 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345#if DEBUG_DISPATCH_CYCLE
1346 ALOGD("dispatchEventToCurrentInputTargets");
1347#endif
1348
1349 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001353 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001354 sp<Connection> connection =
1355 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001356 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001357 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001359 if (DEBUG_FOCUS) {
1360 ALOGD("Dropping event delivery to target with channel '%s' because it "
1361 "is no longer registered with the input dispatcher.",
1362 inputTarget.inputChannel->getName().c_str());
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 }
1366}
1367
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001368void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1369 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1370 // If the policy decides to close the app, we will get a channel removal event via
1371 // unregisterInputChannel, and will clean up the connection that way. We are already not
1372 // sending new pointers to the connection when it blocked, but focused events will continue to
1373 // pile up.
1374 ALOGW("Canceling events for %s because it is unresponsive",
1375 connection->inputChannel->getName().c_str());
1376 if (connection->status == Connection::STATUS_NORMAL) {
1377 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1378 "application not responding");
1379 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381}
1382
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001383void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389 mNoFocusedWindowTimeoutTime = std::nullopt;
1390 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001421bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1422 const char* focusedWindowName) {
1423 if (mAnrTracker.empty()) {
1424 // already processed all events that we waited for
1425 mKeyIsWaitingForEventsTimeout = std::nullopt;
1426 return false;
1427 }
1428
1429 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1430 // Start the timer
1431 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1432 "focus to change",
1433 focusedWindowName);
1434 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1435 return true;
1436 }
1437
1438 // We still have pending events, and already started the timer
1439 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1440 return true; // Still waiting
1441 }
1442
1443 // Waited too long, and some connection still hasn't processed all motions
1444 // Just send the key to the focused window
1445 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1446 focusedWindowName);
1447 mKeyIsWaitingForEventsTimeout = std::nullopt;
1448 return false;
1449}
1450
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001452 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 std::vector<InputTarget>& inputTargets,
1454 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001455 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456
Tiger Huang721e26f2018-07-24 22:26:19 +08001457 int32_t displayId = getTargetDisplayId(entry);
1458 sp<InputWindowHandle> focusedWindowHandle =
1459 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1460 sp<InputApplicationHandle> focusedApplicationHandle =
1461 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1462
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 // If there is no currently focused window and no focused application
1464 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1466 ALOGI("Dropping %s event because there is no focused window or focused application in "
1467 "display %" PRId32 ".",
1468 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001469 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
1471
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001472 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1473 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1474 // start interacting with another application via touch (app switch). This code can be removed
1475 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1476 // an app is expected to have a focused window.
1477 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1478 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1479 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001480 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1481 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1482 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001483 mAwaitedFocusedApplication = focusedApplicationHandle;
1484 ALOGW("Waiting because no window has focus but %s may eventually add a "
1485 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001486 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001487 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1488 return INPUT_EVENT_INJECTION_PENDING;
1489 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1490 // Already raised ANR. Drop the event
1491 ALOGE("Dropping %s event because there is no focused window",
1492 EventEntry::typeToString(entry.type));
1493 return INPUT_EVENT_INJECTION_FAILED;
1494 } else {
1495 // Still waiting for the focused window
1496 return INPUT_EVENT_INJECTION_PENDING;
1497 }
1498 }
1499
1500 // we have a valid, non-null focused window
1501 resetNoFocusedWindowTimeoutLocked();
1502
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001505 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
1507
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001508 if (focusedWindowHandle->getInfo()->paused) {
1509 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1510 return INPUT_EVENT_INJECTION_PENDING;
1511 }
1512
1513 // If the event is a key event, then we must wait for all previous events to
1514 // complete before delivering it because previous events may have the
1515 // side-effect of transferring focus to a different window and we want to
1516 // ensure that the following keys are sent to the new window.
1517 //
1518 // Suppose the user touches a button in a window then immediately presses "A".
1519 // If the button causes a pop-up window to appear then we want to ensure that
1520 // the "A" key is delivered to the new pop-up window. This is because users
1521 // often anticipate pending UI changes when typing on a keyboard.
1522 // To obtain this behavior, we must serialize key events with respect to all
1523 // prior input events.
1524 if (entry.type == EventEntry::Type::KEY) {
1525 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1526 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1527 return INPUT_EVENT_INJECTION_PENDING;
1528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530
1531 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001532 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001533 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1534 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001537 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538}
1539
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001540/**
1541 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1542 * that are currently unresponsive.
1543 */
1544std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1545 const std::vector<TouchedMonitor>& monitors) const {
1546 std::vector<TouchedMonitor> responsiveMonitors;
1547 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1548 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1549 sp<Connection> connection = getConnectionLocked(
1550 monitor.monitor.inputChannel->getConnectionToken());
1551 if (connection == nullptr) {
1552 ALOGE("Could not find connection for monitor %s",
1553 monitor.monitor.inputChannel->getName().c_str());
1554 return false;
1555 }
1556 if (!connection->responsive) {
1557 ALOGW("Unresponsive monitor %s will not get the new gesture",
1558 connection->inputChannel->getName().c_str());
1559 return false;
1560 }
1561 return true;
1562 });
1563 return responsiveMonitors;
1564}
1565
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 std::vector<InputTarget>& inputTargets,
1569 nsecs_t* nextWakeupTime,
1570 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 enum InjectionPermission {
1573 INJECTION_PERMISSION_UNKNOWN,
1574 INJECTION_PERMISSION_GRANTED,
1575 INJECTION_PERMISSION_DENIED
1576 };
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // For security reasons, we defer updating the touch state until we are sure that
1579 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 int32_t displayId = entry.displayId;
1581 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1583
1584 // Update the touch state as needed based on the properties of the touch event.
1585 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1586 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001587 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1588 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001590 // Copy current touch state into tempTouchState.
1591 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1592 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001593 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001594 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001595 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1596 mTouchStatesByDisplay.find(displayId);
1597 if (oldStateIt != mTouchStatesByDisplay.end()) {
1598 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001599 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 }
1601
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001602 bool isSplit = tempTouchState.split;
1603 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1604 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1605 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1607 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1608 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1609 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1610 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 bool wrongDevice = false;
1613 if (newGesture) {
1614 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001615 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001616 ALOGI("Dropping event because a pointer for a different device is already down "
1617 "in display %" PRId32,
1618 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001619 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1621 switchedDevice = false;
1622 wrongDevice = true;
1623 goto Failed;
1624 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001625 tempTouchState.reset();
1626 tempTouchState.down = down;
1627 tempTouchState.deviceId = entry.deviceId;
1628 tempTouchState.source = entry.source;
1629 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001631 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001632 ALOGI("Dropping move event because a pointer for a different device is already active "
1633 "in display %" PRId32,
1634 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001635 // TODO: test multiple simultaneous input streams.
1636 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1637 switchedDevice = false;
1638 wrongDevice = true;
1639 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1643 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1644
Garfield Tan00f511d2019-06-12 16:55:40 -07001645 int32_t x;
1646 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001648 // Always dispatch mouse events to cursor position.
1649 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 x = int32_t(entry.xCursorPosition);
1651 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1654 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001655 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001656 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001657 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001658 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1659 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001660
1661 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001662 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 if (newTouchedWindowHandle != nullptr &&
1667 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001668 // New window supports splitting, but we should never split mouse events.
1669 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 } else if (isSplit) {
1671 // New window does not support splitting but we have already split events.
1672 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001673 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
1675
1676 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001679 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001680 }
1681
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001682 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1683 ALOGI("Not sending touch event to %s because it is paused",
1684 newTouchedWindowHandle->getName().c_str());
1685 newTouchedWindowHandle = nullptr;
1686 }
1687
1688 if (newTouchedWindowHandle != nullptr) {
1689 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1690 if (connection == nullptr) {
1691 ALOGI("Could not find connection for %s",
1692 newTouchedWindowHandle->getName().c_str());
1693 newTouchedWindowHandle = nullptr;
1694 } else if (!connection->responsive) {
1695 // don't send the new touch to an unresponsive window
1696 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1697 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1698 newTouchedWindowHandle = nullptr;
1699 }
1700 }
1701
1702 // Also don't send the new touch event to unresponsive gesture monitors
1703 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1704
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1706 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001707 "(%d, %d) in display %" PRId32 ".",
1708 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001709 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1710 goto Failed;
1711 }
1712
1713 if (newTouchedWindowHandle != nullptr) {
1714 // Set target flags.
1715 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1716 if (isSplit) {
1717 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001719 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1720 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1721 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1722 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1723 }
1724
1725 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001726 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1727 newHoverWindowHandle = nullptr;
1728 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001730 }
1731
1732 // Update the temporary touch state.
1733 BitSet32 pointerIds;
1734 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 pointerIds.markBit(pointerId);
1737 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001738 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 }
1740
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 } else {
1743 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1744
1745 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001746 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001747 if (DEBUG_FOCUS) {
1748 ALOGD("Dropping event because the pointer is not down or we previously "
1749 "dropped the pointer down event in display %" PRId32,
1750 displayId);
1751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1753 goto Failed;
1754 }
1755
1756 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001758 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1760 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001763 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001764 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1766 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001767 if (DEBUG_FOCUS) {
1768 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1769 oldTouchedWindowHandle->getName().c_str(),
1770 newTouchedWindowHandle->getName().c_str(), displayId);
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001773 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1774 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1775 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 // Make a slippery entrance into the new window.
1778 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1779 isSplit = true;
1780 }
1781
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 int32_t targetFlags =
1783 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 if (isSplit) {
1785 targetFlags |= InputTarget::FLAG_SPLIT;
1786 }
1787 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1788 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1789 }
1790
1791 BitSet32 pointerIds;
1792 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001795 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
1797 }
1798 }
1799
1800 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001801 // Let the previous window know that the hover sequence is over, unless we already did it
1802 // when dispatching it as is to newTouchedWindowHandle.
1803 if (mLastHoverWindowHandle != nullptr &&
1804 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1805 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#if DEBUG_HOVER
1807 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1811 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 }
1813
Garfield Tandf26e862020-07-01 20:18:19 -07001814 // Let the new window know that the hover sequence is starting, unless we already did it
1815 // when dispatching it as is to newTouchedWindowHandle.
1816 if (newHoverWindowHandle != nullptr &&
1817 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1818 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819#if DEBUG_HOVER
1820 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1824 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1825 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828
1829 // Check permission to inject into all touched foreground windows and ensure there
1830 // is at least one touched foreground window.
1831 {
1832 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1835 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1838 injectionPermission = INJECTION_PERMISSION_DENIED;
1839 goto Failed;
1840 }
1841 }
1842 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001844 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001845 ALOGI("Dropping event because there is no touched foreground window in display "
1846 "%" PRId32 " or gesture monitor to receive it.",
1847 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1849 goto Failed;
1850 }
1851
1852 // Permission granted to injection into all touched foreground windows.
1853 injectionPermission = INJECTION_PERMISSION_GRANTED;
1854 }
1855
1856 // Check whether windows listening for outside touches are owned by the same UID. If it is
1857 // set the policy flag that we will not reveal coordinate information to this window.
1858 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1859 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 if (foregroundWindowHandle) {
1862 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001863 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001864 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1865 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1866 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1868 InputTarget::FLAG_ZERO_COORDS,
1869 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872 }
1873 }
1874 }
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // If this is the first pointer going down and the touched window has a wallpaper
1877 // then also add the touched wallpaper windows so they are locked in for the duration
1878 // of the touch gesture.
1879 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1880 // engine only supports touch events. We would need to add a mechanism similar
1881 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1882 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1883 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001884 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001885 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001886 const std::vector<sp<InputWindowHandle>> windowHandles =
1887 getWindowHandlesLocked(displayId);
1888 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001891 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001892 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 .addOrUpdateWindow(windowHandle,
1894 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1895 InputTarget::
1896 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1897 InputTarget::FLAG_DISPATCH_AS_IS,
1898 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
1900 }
1901 }
1902 }
1903
1904 // Success! Output targets.
1905 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1906
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001909 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001912 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001913 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001914 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 }
1916
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 // Drop the outside or hover touch windows since we will not care about them
1918 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001919 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920
1921Failed:
1922 // Check injection permission once and for all.
1923 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 injectionPermission = INJECTION_PERMISSION_GRANTED;
1926 } else {
1927 injectionPermission = INJECTION_PERMISSION_DENIED;
1928 }
1929 }
1930
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001931 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1932 return injectionResult;
1933 }
1934
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001936 if (!wrongDevice) {
1937 if (switchedDevice) {
1938 if (DEBUG_FOCUS) {
1939 ALOGD("Conflicting pointer actions: Switched to a different device.");
1940 }
1941 *outConflictingPointerActions = true;
1942 }
1943
1944 if (isHoverAction) {
1945 // Started hovering, therefore no longer down.
1946 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001947 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001948 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1949 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 *outConflictingPointerActions = true;
1952 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001953 tempTouchState.reset();
1954 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1955 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1956 tempTouchState.deviceId = entry.deviceId;
1957 tempTouchState.source = entry.source;
1958 tempTouchState.displayId = displayId;
1959 }
1960 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1961 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1962 // All pointers up or canceled.
1963 tempTouchState.reset();
1964 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1965 // First pointer went down.
1966 if (oldState && oldState->down) {
1967 if (DEBUG_FOCUS) {
1968 ALOGD("Conflicting pointer actions: Down received while already down.");
1969 }
1970 *outConflictingPointerActions = true;
1971 }
1972 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1973 // One pointer went up.
1974 if (isSplit) {
1975 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1976 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 for (size_t i = 0; i < tempTouchState.windows.size();) {
1979 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1980 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1981 touchedWindow.pointerIds.clearBit(pointerId);
1982 if (touchedWindow.pointerIds.isEmpty()) {
1983 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1984 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001989 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001991
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 // Save changes unless the action was scroll in which case the temporary touch
1993 // state was only valid for this one action.
1994 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1995 if (tempTouchState.displayId >= 0) {
1996 mTouchStatesByDisplay[displayId] = tempTouchState;
1997 } else {
1998 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002002 // Update hover state.
2003 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 return injectionResult;
2007}
2008
2009void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010 int32_t targetFlags, BitSet32 pointerIds,
2011 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002012 std::vector<InputTarget>::iterator it =
2013 std::find_if(inputTargets.begin(), inputTargets.end(),
2014 [&windowHandle](const InputTarget& inputTarget) {
2015 return inputTarget.inputChannel->getConnectionToken() ==
2016 windowHandle->getToken();
2017 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002018
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002019 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002020
2021 if (it == inputTargets.end()) {
2022 InputTarget inputTarget;
2023 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2024 if (inputChannel == nullptr) {
2025 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2026 return;
2027 }
2028 inputTarget.inputChannel = inputChannel;
2029 inputTarget.flags = targetFlags;
2030 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2031 inputTargets.push_back(inputTarget);
2032 it = inputTargets.end() - 1;
2033 }
2034
2035 ALOG_ASSERT(it->flags == targetFlags);
2036 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2037
2038 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2039 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040}
2041
Michael Wright3dd60e22019-03-27 22:06:44 +00002042void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 int32_t displayId, float xOffset,
2044 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2046 mGlobalMonitorsByDisplay.find(displayId);
2047
2048 if (it != mGlobalMonitorsByDisplay.end()) {
2049 const std::vector<Monitor>& monitors = it->second;
2050 for (const Monitor& monitor : monitors) {
2051 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054}
2055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2057 float yOffset,
2058 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 InputTarget target;
2060 target.inputChannel = monitor.inputChannel;
2061 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002062 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 inputTargets.push_back(target);
2064}
2065
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002067 const InjectionState* injectionState) {
2068 if (injectionState &&
2069 (windowHandle == nullptr ||
2070 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2071 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002072 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 "owned by uid %d",
2075 injectionState->injectorPid, injectionState->injectorUid,
2076 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 } else {
2078 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081 return false;
2082 }
2083 return true;
2084}
2085
Robert Carrc9bf1d32020-04-13 17:21:08 -07002086/**
2087 * Indicate whether one window handle should be considered as obscuring
2088 * another window handle. We only check a few preconditions. Actually
2089 * checking the bounds is left to the caller.
2090 */
2091static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2092 const sp<InputWindowHandle>& otherHandle) {
2093 // Compare by token so cloned layers aren't counted
2094 if (haveSameToken(windowHandle, otherHandle)) {
2095 return false;
2096 }
2097 auto info = windowHandle->getInfo();
2098 auto otherInfo = otherHandle->getInfo();
2099 if (!otherInfo->visible) {
2100 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002101 } else if (info->ownerPid == otherInfo->ownerPid) {
2102 // If ownerPid is the same we don't generate occlusion events as there
2103 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002104 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002105 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002106 return false;
2107 } else if (otherInfo->displayId != info->displayId) {
2108 return false;
2109 }
2110 return true;
2111}
2112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002113bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2114 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002116 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2117 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002118 if (windowHandle == otherHandle) {
2119 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002122 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002123 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 return true;
2125 }
2126 }
2127 return false;
2128}
2129
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002130bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2131 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002132 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002133 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002134 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002135 if (windowHandle == otherHandle) {
2136 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002137 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002138 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002139 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002140 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002141 return true;
2142 }
2143 }
2144 return false;
2145}
2146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002147std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 const sp<InputApplicationHandle>& applicationHandle,
2149 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002150 if (applicationHandle != nullptr) {
2151 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002152 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 } else {
2154 return applicationHandle->getName();
2155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002157 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161}
2162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 if (eventEntry.type == EventEntry::Type::FOCUS) {
2165 // Focus events are passed to apps, but do not represent user activity.
2166 return;
2167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002168 int32_t displayId = getTargetDisplayId(eventEntry);
2169 sp<InputWindowHandle> focusedWindowHandle =
2170 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2171 if (focusedWindowHandle != nullptr) {
2172 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002173 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002175 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 return;
2178 }
2179 }
2180
2181 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002183 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2185 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 return;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 eventType = USER_ACTIVITY_EVENT_TOUCH;
2191 }
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2196 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 return;
2198 }
2199 eventType = USER_ACTIVITY_EVENT_BUTTON;
2200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002202 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::CONFIGURATION_CHANGED:
2204 case EventEntry::Type::DEVICE_RESET: {
2205 LOG_ALWAYS_FATAL("%s events are not user activity",
2206 EventEntry::typeToString(eventEntry.type));
2207 break;
2208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002211 std::unique_ptr<CommandEntry> commandEntry =
2212 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
2218void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 const sp<Connection>& connection,
2220 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002221 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002224 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002225 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 ATRACE_NAME(message.c_str());
2227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#if DEBUG_DISPATCH_CYCLE
2229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002230 "globalScaleFactor=%f, pointerIds=0x%x %s",
2231 connection->getInputChannelName().c_str(), inputTarget.flags,
2232 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2233 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235
2236 // Skip this event if the connection status is not normal.
2237 // We don't want to enqueue additional outbound events if the connection is broken.
2238 if (connection->status != Connection::STATUS_NORMAL) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243 return;
2244 }
2245
2246 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2249 "Entry type %s should not have FLAG_SPLIT",
2250 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (!splitMotionEntry) {
2257 return; // split event was dropped
2258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
2260 ALOGD("channel '%s' ~ Split motion event.",
2261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 splitMotionEntry->release();
2266 return;
2267 }
2268 }
2269
2270 // Not splitting. Enqueue dispatch entries for the event as is.
2271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2272}
2273
2274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 const sp<Connection>& connection,
2276 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002277 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002280 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002281 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 ATRACE_NAME(message.c_str());
2283 }
2284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 startDispatchCycleLocked(currentTime, connection);
2304 }
2305}
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2308 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2313 connection->getInputChannelName().c_str(),
2314 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 ATRACE_NAME(message.c_str());
2316 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (!(inputTargetFlags & dispatchMode)) {
2319 return;
2320 }
2321 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2322
2323 // This is a new event.
2324 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002325 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2329 // different EventEntry than what was passed in.
2330 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002335 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336 dispatchEntry->resolvedAction = keyEntry.action;
2337 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2340 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 return; // skip the inconsistent event
2346 }
2347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002350 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002352 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2353 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2354 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2355 static_cast<int32_t>(IdGenerator::Source::OTHER);
2356 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2367 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002369 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 }
2371 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2373 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2385 }
2386 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2391 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2394 "event",
2395 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 return; // skip the inconsistent event
2398 }
2399
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002400 dispatchEntry->resolvedEventId =
2401 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2402 ? mIdGenerator.nextId()
2403 : motionEntry.id;
2404 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2405 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2406 ") to MotionEvent(id=0x%" PRIx32 ").",
2407 motionEntry.id, dispatchEntry->resolvedEventId);
2408 ATRACE_NAME(message.c_str());
2409 }
2410
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413
2414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002416 case EventEntry::Type::FOCUS: {
2417 break;
2418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002419 case EventEntry::Type::CONFIGURATION_CHANGED:
2420 case EventEntry::Type::DEVICE_RESET: {
2421 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 break;
2424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 // Remember that we are waiting for this dispatch to complete.
2428 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002429 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002433 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002434 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002435}
2436
chaviwfd6d3512019-03-25 13:23:49 -07002437void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002439 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002440 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2441 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002442 return;
2443 }
2444
2445 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2446 if (inputWindowHandle == nullptr) {
2447 return;
2448 }
2449
chaviw8c9cf542019-03-25 13:02:48 -07002450 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002451 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002452
2453 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2454
2455 if (!hasFocusChanged) {
2456 return;
2457 }
2458
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002459 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2460 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002461 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002462 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463}
2464
2465void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002467 if (ATRACE_ENABLED()) {
2468 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002470 ATRACE_NAME(message.c_str());
2471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474#endif
2475
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002476 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2477 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002479 const nsecs_t timeout =
2480 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2481 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
2483 // Publish the event.
2484 status_t status;
2485 EventEntry* eventEntry = dispatchEntry->eventEntry;
2486 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002487 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002488 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2489 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002492 status =
2493 connection->inputPublisher
2494 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2495 keyEntry->deviceId, keyEntry->source,
2496 keyEntry->displayId, std::move(hmac),
2497 dispatchEntry->resolvedAction,
2498 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2499 keyEntry->scanCode, keyEntry->metaState,
2500 keyEntry->repeatCount, keyEntry->downTime,
2501 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002505 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 PointerCoords scaledCoords[MAX_POINTERS];
2509 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2510
chaviw82357092020-01-28 13:13:06 -08002511 // Set the X and Y offset and X and Y scale depending on the input source.
2512 float xOffset = 0.0f, yOffset = 0.0f;
2513 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002514 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2515 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2516 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002517 xScale = dispatchEntry->windowXScale;
2518 yScale = dispatchEntry->windowYScale;
2519 xOffset = dispatchEntry->xOffset * xScale;
2520 yOffset = dispatchEntry->yOffset * yScale;
2521 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2523 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002524 // Don't apply window scale here since we don't want scale to affect raw
2525 // coordinates. The scale will be sent back to the client and applied
2526 // later when requesting relative coordinates.
2527 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2528 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 }
2530 usingCoords = scaledCoords;
2531 }
2532 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 // We don't want the dispatch target to know.
2534 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2535 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2536 scaledCoords[i].clear();
2537 }
2538 usingCoords = scaledCoords;
2539 }
2540 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002541
2542 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543
2544 // Publish the motion event.
2545 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002546 .publishMotionEvent(dispatchEntry->seq,
2547 dispatchEntry->resolvedEventId,
2548 motionEntry->deviceId, motionEntry->source,
2549 motionEntry->displayId, std::move(hmac),
2550 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 motionEntry->actionButton,
2552 dispatchEntry->resolvedFlags,
2553 motionEntry->edgeFlags, motionEntry->metaState,
2554 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002555 motionEntry->classification, xScale, yScale,
2556 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 motionEntry->yPrecision,
2558 motionEntry->xCursorPosition,
2559 motionEntry->yCursorPosition,
2560 motionEntry->downTime, motionEntry->eventTime,
2561 motionEntry->pointerCount,
2562 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002563 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 break;
2565 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002566 case EventEntry::Type::FOCUS: {
2567 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2568 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002569 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002570 focusEntry->hasFocus,
2571 mInTouchMode);
2572 break;
2573 }
2574
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002575 case EventEntry::Type::CONFIGURATION_CHANGED:
2576 case EventEntry::Type::DEVICE_RESET: {
2577 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2578 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
2583 // Check the result.
2584 if (status) {
2585 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002586 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 "This is unexpected because the wait queue is empty, so the pipe "
2589 "should be empty and we shouldn't have any problems writing an "
2590 "event to it, status=%d",
2591 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2593 } else {
2594 // Pipe is full and we are waiting for the app to finish process some events
2595 // before sending more events to it.
2596#if DEBUG_DISPATCH_CYCLE
2597 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 "waiting for the application to catch up",
2599 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602 } else {
2603 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604 "status=%d",
2605 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2607 }
2608 return;
2609 }
2610
2611 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002612 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2613 connection->outboundQueue.end(),
2614 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002615 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002616 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002617 if (connection->responsive) {
2618 mAnrTracker.insert(dispatchEntry->timeoutTime,
2619 connection->inputChannel->getConnectionToken());
2620 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002621 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 }
2623}
2624
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002625const std::array<uint8_t, 32> InputDispatcher::getSignature(
2626 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2627 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2628 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2629 // Only sign events up and down events as the purely move events
2630 // are tied to their up/down counterparts so signing would be redundant.
2631 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2632 verifiedEvent.actionMasked = actionMasked;
2633 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2634 return mHmacKeyManager.sign(verifiedEvent);
2635 }
2636 return INVALID_HMAC;
2637}
2638
2639const std::array<uint8_t, 32> InputDispatcher::getSignature(
2640 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2641 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2642 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2643 verifiedEvent.action = dispatchEntry.resolvedAction;
2644 return mHmacKeyManager.sign(verifiedEvent);
2645}
2646
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 const sp<Connection>& connection, uint32_t seq,
2649 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650#if DEBUG_DISPATCH_CYCLE
2651 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653#endif
2654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 if (connection->status == Connection::STATUS_BROKEN ||
2656 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 return;
2658 }
2659
2660 // Notify other system components and prepare to start the next dispatch cycle.
2661 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2662}
2663
2664void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 const sp<Connection>& connection,
2666 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#if DEBUG_DISPATCH_CYCLE
2668 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670#endif
2671
2672 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002673 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002674 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002675 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002676 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677
2678 // The connection appears to be unrecoverably broken.
2679 // Ignore already broken or zombie connections.
2680 if (connection->status == Connection::STATUS_NORMAL) {
2681 connection->status = Connection::STATUS_BROKEN;
2682
2683 if (notify) {
2684 // Notify other system components.
2685 onDispatchCycleBrokenLocked(currentTime, connection);
2686 }
2687 }
2688}
2689
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002690void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2691 while (!queue.empty()) {
2692 DispatchEntry* dispatchEntry = queue.front();
2693 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002694 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
2696}
2697
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002698void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002700 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
2702 delete dispatchEntry;
2703}
2704
2705int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2706 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2707
2708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002709 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002711 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002713 "fd=%d, events=0x%x",
2714 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 return 0; // remove the callback
2716 }
2717
2718 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002719 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2721 if (!(events & ALOOPER_EVENT_INPUT)) {
2722 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 "events=0x%x",
2724 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 return 1;
2726 }
2727
2728 nsecs_t currentTime = now();
2729 bool gotOne = false;
2730 status_t status;
2731 for (;;) {
2732 uint32_t seq;
2733 bool handled;
2734 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2735 if (status) {
2736 break;
2737 }
2738 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2739 gotOne = true;
2740 }
2741 if (gotOne) {
2742 d->runCommandsLockedInterruptible();
2743 if (status == WOULD_BLOCK) {
2744 return 1;
2745 }
2746 }
2747
2748 notify = status != DEAD_OBJECT || !connection->monitor;
2749 if (notify) {
2750 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753 } else {
2754 // Monitor channels are never explicitly unregistered.
2755 // We do it automatically when the remote endpoint is closed so don't warn
2756 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002757 const bool stillHaveWindowHandle =
2758 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2759 nullptr;
2760 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 if (notify) {
2762 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 "events=0x%x",
2764 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
2766 }
2767
2768 // Unregister the channel.
2769 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2770 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772}
2773
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002776 for (const auto& pair : mConnectionsByFd) {
2777 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 }
2779}
2780
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002782 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002783 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2784 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2785}
2786
2787void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2788 const CancelationOptions& options,
2789 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2790 for (const auto& it : monitorsByDisplay) {
2791 const std::vector<Monitor>& monitors = it.second;
2792 for (const Monitor& monitor : monitors) {
2793 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002794 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002795 }
2796}
2797
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2799 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002800 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002801 if (connection == nullptr) {
2802 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002804
2805 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806}
2807
2808void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2809 const sp<Connection>& connection, const CancelationOptions& options) {
2810 if (connection->status == Connection::STATUS_BROKEN) {
2811 return;
2812 }
2813
2814 nsecs_t currentTime = now();
2815
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002816 std::vector<EventEntry*> cancelationEvents =
2817 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002819 if (cancelationEvents.empty()) {
2820 return;
2821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002823 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2824 "with reality: %s, mode=%d.",
2825 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2826 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002828
2829 InputTarget target;
2830 sp<InputWindowHandle> windowHandle =
2831 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2832 if (windowHandle != nullptr) {
2833 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2834 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2835 windowInfo->windowXScale, windowInfo->windowYScale);
2836 target.globalScaleFactor = windowInfo->globalScaleFactor;
2837 }
2838 target.inputChannel = connection->inputChannel;
2839 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2840
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002841 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2842 EventEntry* cancelationEventEntry = cancelationEvents[i];
2843 switch (cancelationEventEntry->type) {
2844 case EventEntry::Type::KEY: {
2845 logOutboundKeyDetails("cancel - ",
2846 static_cast<const KeyEntry&>(*cancelationEventEntry));
2847 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002849 case EventEntry::Type::MOTION: {
2850 logOutboundMotionDetails("cancel - ",
2851 static_cast<const MotionEntry&>(*cancelationEventEntry));
2852 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002854 case EventEntry::Type::FOCUS: {
2855 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2856 break;
2857 }
2858 case EventEntry::Type::CONFIGURATION_CHANGED:
2859 case EventEntry::Type::DEVICE_RESET: {
2860 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2861 EventEntry::typeToString(cancelationEventEntry->type));
2862 break;
2863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
2865
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002866 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2867 target, InputTarget::FLAG_DISPATCH_AS_IS);
2868
2869 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002871
2872 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873}
2874
Svet Ganov5d3bc372020-01-26 23:11:07 -08002875void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2876 const sp<Connection>& connection) {
2877 if (connection->status == Connection::STATUS_BROKEN) {
2878 return;
2879 }
2880
2881 nsecs_t currentTime = now();
2882
2883 std::vector<EventEntry*> downEvents =
2884 connection->inputState.synthesizePointerDownEvents(currentTime);
2885
2886 if (downEvents.empty()) {
2887 return;
2888 }
2889
2890#if DEBUG_OUTBOUND_EVENT_DETAILS
2891 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2892 connection->getInputChannelName().c_str(), downEvents.size());
2893#endif
2894
2895 InputTarget target;
2896 sp<InputWindowHandle> windowHandle =
2897 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2898 if (windowHandle != nullptr) {
2899 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2900 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2901 windowInfo->windowXScale, windowInfo->windowYScale);
2902 target.globalScaleFactor = windowInfo->globalScaleFactor;
2903 }
2904 target.inputChannel = connection->inputChannel;
2905 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2906
2907 for (EventEntry* downEventEntry : downEvents) {
2908 switch (downEventEntry->type) {
2909 case EventEntry::Type::MOTION: {
2910 logOutboundMotionDetails("down - ",
2911 static_cast<const MotionEntry&>(*downEventEntry));
2912 break;
2913 }
2914
2915 case EventEntry::Type::KEY:
2916 case EventEntry::Type::FOCUS:
2917 case EventEntry::Type::CONFIGURATION_CHANGED:
2918 case EventEntry::Type::DEVICE_RESET: {
2919 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2920 EventEntry::typeToString(downEventEntry->type));
2921 break;
2922 }
2923 }
2924
2925 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2926 target, InputTarget::FLAG_DISPATCH_AS_IS);
2927
2928 downEventEntry->release();
2929 }
2930
2931 startDispatchCycleLocked(currentTime, connection);
2932}
2933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002934MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002935 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 ALOG_ASSERT(pointerIds.value != 0);
2937
2938 uint32_t splitPointerIndexMap[MAX_POINTERS];
2939 PointerProperties splitPointerProperties[MAX_POINTERS];
2940 PointerCoords splitPointerCoords[MAX_POINTERS];
2941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002942 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 uint32_t splitPointerCount = 0;
2944
2945 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 uint32_t pointerId = uint32_t(pointerProperties.id);
2950 if (pointerIds.hasBit(pointerId)) {
2951 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2952 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2953 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002954 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 splitPointerCount += 1;
2956 }
2957 }
2958
2959 if (splitPointerCount != pointerIds.count()) {
2960 // This is bad. We are missing some of the pointers that we expected to deliver.
2961 // Most likely this indicates that we received an ACTION_MOVE events that has
2962 // different pointer ids than we expected based on the previous ACTION_DOWN
2963 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2964 // in this way.
2965 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 "we expected there to be %d pointers. This probably means we received "
2967 "a broken sequence of pointer ids from the input device.",
2968 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002969 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
2971
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002972 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2975 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2977 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002978 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 uint32_t pointerId = uint32_t(pointerProperties.id);
2980 if (pointerIds.hasBit(pointerId)) {
2981 if (pointerIds.count() == 1) {
2982 // The first/last pointer went down/up.
2983 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 ? AMOTION_EVENT_ACTION_DOWN
2985 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 } else {
2987 // A secondary pointer went down/up.
2988 uint32_t splitPointerIndex = 0;
2989 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2990 splitPointerIndex += 1;
2991 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 action = maskedAction |
2993 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995 } else {
2996 // An unrelated pointer changed.
2997 action = AMOTION_EVENT_ACTION_MOVE;
2998 }
2999 }
3000
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003001 int32_t newId = mIdGenerator.nextId();
3002 if (ATRACE_ENABLED()) {
3003 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3004 ") to MotionEvent(id=0x%" PRIx32 ").",
3005 originalMotionEntry.id, newId);
3006 ATRACE_NAME(message.c_str());
3007 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003008 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003009 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3010 originalMotionEntry.source, originalMotionEntry.displayId,
3011 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 originalMotionEntry.actionButton, originalMotionEntry.flags,
3013 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3014 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3015 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3016 originalMotionEntry.xCursorPosition,
3017 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003018 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003020 if (originalMotionEntry.injectionState) {
3021 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 splitMotionEntry->injectionState->refCount += 1;
3023 }
3024
3025 return splitMotionEntry;
3026}
3027
3028void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3029#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003030 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031#endif
3032
3033 bool needWake;
3034 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003035 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036
Prabir Pradhan42611e02018-11-27 14:04:02 -08003037 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003038 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 needWake = enqueueInboundEventLocked(newEntry);
3040 } // release lock
3041
3042 if (needWake) {
3043 mLooper->wake();
3044 }
3045}
3046
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003047/**
3048 * If one of the meta shortcuts is detected, process them here:
3049 * Meta + Backspace -> generate BACK
3050 * Meta + Enter -> generate HOME
3051 * This will potentially overwrite keyCode and metaState.
3052 */
3053void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003055 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3056 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3057 if (keyCode == AKEYCODE_DEL) {
3058 newKeyCode = AKEYCODE_BACK;
3059 } else if (keyCode == AKEYCODE_ENTER) {
3060 newKeyCode = AKEYCODE_HOME;
3061 }
3062 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003063 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003064 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003065 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003066 keyCode = newKeyCode;
3067 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3068 }
3069 } else if (action == AKEY_EVENT_ACTION_UP) {
3070 // In order to maintain a consistent stream of up and down events, check to see if the key
3071 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3072 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003073 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003074 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003075 auto replacementIt = mReplacedKeys.find(replacement);
3076 if (replacementIt != mReplacedKeys.end()) {
3077 keyCode = replacementIt->second;
3078 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003079 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3080 }
3081 }
3082}
3083
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3085#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3087 "policyFlags=0x%x, action=0x%x, "
3088 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3089 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3090 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3091 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#endif
3093 if (!validateKeyEvent(args->action)) {
3094 return;
3095 }
3096
3097 uint32_t policyFlags = args->policyFlags;
3098 int32_t flags = args->flags;
3099 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003100 // InputDispatcher tracks and generates key repeats on behalf of
3101 // whatever notifies it, so repeatCount should always be set to 0
3102 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3104 policyFlags |= POLICY_FLAG_VIRTUAL;
3105 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 if (policyFlags & POLICY_FLAG_FUNCTION) {
3108 metaState |= AMETA_FUNCTION_ON;
3109 }
3110
3111 policyFlags |= POLICY_FLAG_TRUSTED;
3112
Michael Wright78f24442014-08-06 15:55:28 -07003113 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003114 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003115
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003117 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003118 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3119 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120
Michael Wright2b3c3302018-03-02 17:19:13 +00003121 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003123 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3124 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 bool needWake;
3129 { // acquire lock
3130 mLock.lock();
3131
3132 if (shouldSendKeyToInputFilterLocked(args)) {
3133 mLock.unlock();
3134
3135 policyFlags |= POLICY_FLAG_FILTERED;
3136 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3137 return; // event was consumed by the filter
3138 }
3139
3140 mLock.lock();
3141 }
3142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003144 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 args->displayId, policyFlags, args->action, flags, keyCode,
3146 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147
3148 needWake = enqueueInboundEventLocked(newEntry);
3149 mLock.unlock();
3150 } // release lock
3151
3152 if (needWake) {
3153 mLooper->wake();
3154 }
3155}
3156
3157bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3158 return mInputFilterEnabled;
3159}
3160
3161void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3162#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003163 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3164 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003165 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3166 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003167 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003168 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3169 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3170 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3171 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 for (uint32_t i = 0; i < args->pointerCount; i++) {
3173 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 "x=%f, y=%f, pressure=%f, size=%f, "
3175 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3176 "orientation=%f",
3177 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3178 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3179 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3180 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3181 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3182 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3183 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3184 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3185 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3186 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 }
3188#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3190 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 return;
3192 }
3193
3194 uint32_t policyFlags = args->policyFlags;
3195 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003196
3197 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003198 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003199 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3200 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
3204 bool needWake;
3205 { // acquire lock
3206 mLock.lock();
3207
3208 if (shouldSendMotionToInputFilterLocked(args)) {
3209 mLock.unlock();
3210
3211 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003212 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3213 args->action, args->actionButton, args->flags, args->edgeFlags,
3214 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3215 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3216 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3217 args->downTime, args->eventTime, args->pointerCount,
3218 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
3220 policyFlags |= POLICY_FLAG_FILTERED;
3221 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3222 return; // event was consumed by the filter
3223 }
3224
3225 mLock.lock();
3226 }
3227
3228 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003229 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003230 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003231 args->displayId, policyFlags, args->action, args->actionButton,
3232 args->flags, args->metaState, args->buttonState,
3233 args->classification, args->edgeFlags, args->xPrecision,
3234 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3235 args->downTime, args->pointerCount, args->pointerProperties,
3236 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237
3238 needWake = enqueueInboundEventLocked(newEntry);
3239 mLock.unlock();
3240 } // release lock
3241
3242 if (needWake) {
3243 mLooper->wake();
3244 }
3245}
3246
3247bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003248 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249}
3250
3251void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3252#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003253 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 "switchMask=0x%08x",
3255 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256#endif
3257
3258 uint32_t policyFlags = args->policyFlags;
3259 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003260 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261}
3262
3263void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3264#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3266 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267#endif
3268
3269 bool needWake;
3270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
Prabir Pradhan42611e02018-11-27 14:04:02 -08003273 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003274 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 needWake = enqueueInboundEventLocked(newEntry);
3276 } // release lock
3277
3278 if (needWake) {
3279 mLooper->wake();
3280 }
3281}
3282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3284 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003285 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286#if DEBUG_INBOUND_EVENT_DETAILS
3287 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003288 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3289 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#endif
3291
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003292 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293
3294 policyFlags |= POLICY_FLAG_INJECTED;
3295 if (hasInjectionPermission(injectorPid, injectorUid)) {
3296 policyFlags |= POLICY_FLAG_TRUSTED;
3297 }
3298
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003299 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003302 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3303 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 if (!validateKeyEvent(action)) {
3305 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003308 int32_t flags = incomingKey.getFlags();
3309 int32_t keyCode = incomingKey.getKeyCode();
3310 int32_t metaState = incomingKey.getMetaState();
3311 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003313 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003314 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003315 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3316 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3317 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3320 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003321 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322
3323 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3324 android::base::Timer t;
3325 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3326 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3327 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3328 std::to_string(t.duration().count()).c_str());
3329 }
3330 }
3331
3332 mLock.lock();
3333 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003334 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3335 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003336 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3337 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003338 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 injectedEntries.push(injectedEntry);
3340 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
3342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 case AINPUT_EVENT_TYPE_MOTION: {
3344 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3345 int32_t action = motionEvent->getAction();
3346 size_t pointerCount = motionEvent->getPointerCount();
3347 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3348 int32_t actionButton = motionEvent->getActionButton();
3349 int32_t displayId = motionEvent->getDisplayId();
3350 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3351 return INPUT_EVENT_INJECTION_FAILED;
3352 }
3353
3354 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3355 nsecs_t eventTime = motionEvent->getEventTime();
3356 android::base::Timer t;
3357 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3358 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3359 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3360 std::to_string(t.duration().count()).c_str());
3361 }
3362 }
3363
3364 mLock.lock();
3365 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3366 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3367 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003368 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3369 motionEvent->getSource(), motionEvent->getDisplayId(),
3370 policyFlags, action, actionButton, motionEvent->getFlags(),
3371 motionEvent->getMetaState(), motionEvent->getButtonState(),
3372 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3373 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003374 motionEvent->getRawXCursorPosition(),
3375 motionEvent->getRawYCursorPosition(),
3376 motionEvent->getDownTime(), uint32_t(pointerCount),
3377 pointerProperties, samplePointerCoords,
3378 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 injectedEntries.push(injectedEntry);
3380 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3381 sampleEventTimes += 1;
3382 samplePointerCoords += pointerCount;
3383 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003384 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003385 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 motionEvent->getDisplayId(), policyFlags, action,
3387 actionButton, motionEvent->getFlags(),
3388 motionEvent->getMetaState(), motionEvent->getButtonState(),
3389 motionEvent->getClassification(),
3390 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3391 motionEvent->getYPrecision(),
3392 motionEvent->getRawXCursorPosition(),
3393 motionEvent->getRawYCursorPosition(),
3394 motionEvent->getDownTime(), uint32_t(pointerCount),
3395 pointerProperties, samplePointerCoords,
3396 motionEvent->getXOffset(), motionEvent->getYOffset());
3397 injectedEntries.push(nextInjectedEntry);
3398 }
3399 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003402 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003403 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406
3407 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3408 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3409 injectionState->injectionIsAsync = true;
3410 }
3411
3412 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003413 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
3415 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003416 while (!injectedEntries.empty()) {
3417 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3418 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420
3421 mLock.unlock();
3422
3423 if (needWake) {
3424 mLooper->wake();
3425 }
3426
3427 int32_t injectionResult;
3428 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003429 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
3431 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3432 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3433 } else {
3434 for (;;) {
3435 injectionResult = injectionState->injectionResult;
3436 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3437 break;
3438 }
3439
3440 nsecs_t remainingTimeout = endTime - now();
3441 if (remainingTimeout <= 0) {
3442#if DEBUG_INJECTION
3443 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445#endif
3446 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3447 break;
3448 }
3449
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003450 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3454 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 while (injectionState->pendingForegroundDispatches != 0) {
3456#if DEBUG_INJECTION
3457 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460 nsecs_t remainingTimeout = endTime - now();
3461 if (remainingTimeout <= 0) {
3462#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3464 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465#endif
3466 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3467 break;
3468 }
3469
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003470 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472 }
3473 }
3474
3475 injectionState->release();
3476 } // release lock
3477
3478#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003479 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481#endif
3482
3483 return injectionResult;
3484}
3485
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003486std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003487 std::array<uint8_t, 32> calculatedHmac;
3488 std::unique_ptr<VerifiedInputEvent> result;
3489 switch (event.getType()) {
3490 case AINPUT_EVENT_TYPE_KEY: {
3491 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3492 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3493 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3494 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3495 break;
3496 }
3497 case AINPUT_EVENT_TYPE_MOTION: {
3498 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3499 VerifiedMotionEvent verifiedMotionEvent =
3500 verifiedMotionEventFromMotionEvent(motionEvent);
3501 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3502 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3503 break;
3504 }
3505 default: {
3506 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3507 return nullptr;
3508 }
3509 }
3510 if (calculatedHmac == INVALID_HMAC) {
3511 return nullptr;
3512 }
3513 if (calculatedHmac != event.getHmac()) {
3514 return nullptr;
3515 }
3516 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003517}
3518
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 return injectorUid == 0 ||
3521 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522}
3523
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003524void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 InjectionState* injectionState = entry->injectionState;
3526 if (injectionState) {
3527#if DEBUG_INJECTION
3528 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 "injectorPid=%d, injectorUid=%d",
3530 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531#endif
3532
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003533 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 // Log the outcome since the injector did not wait for the injection result.
3535 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536 case INPUT_EVENT_INJECTION_SUCCEEDED:
3537 ALOGV("Asynchronous input event injection succeeded.");
3538 break;
3539 case INPUT_EVENT_INJECTION_FAILED:
3540 ALOGW("Asynchronous input event injection failed.");
3541 break;
3542 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3543 ALOGW("Asynchronous input event injection permission denied.");
3544 break;
3545 case INPUT_EVENT_INJECTION_TIMED_OUT:
3546 ALOGW("Asynchronous input event injection timed out.");
3547 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549 }
3550
3551 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003552 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554}
3555
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003556void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 InjectionState* injectionState = entry->injectionState;
3558 if (injectionState) {
3559 injectionState->pendingForegroundDispatches += 1;
3560 }
3561}
3562
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003563void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 InjectionState* injectionState = entry->injectionState;
3565 if (injectionState) {
3566 injectionState->pendingForegroundDispatches -= 1;
3567
3568 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003569 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 }
3571 }
3572}
3573
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003574std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3575 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003576 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577}
3578
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003580 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003581 if (windowHandleToken == nullptr) {
3582 return nullptr;
3583 }
3584
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003586 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3587 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003588 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003589 return windowHandle;
3590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003593 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594}
3595
Mady Mellor017bcd12020-06-23 19:12:00 +00003596bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3597 for (auto& it : mWindowHandlesByDisplay) {
3598 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3599 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003600 if (handle->getId() == windowHandle->getId() &&
3601 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003602 if (windowHandle->getInfo()->displayId != it.first) {
3603 ALOGE("Found window %s in display %" PRId32
3604 ", but it should belong to display %" PRId32,
3605 windowHandle->getName().c_str(), it.first,
3606 windowHandle->getInfo()->displayId);
3607 }
3608 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611 }
3612 return false;
3613}
3614
Robert Carr5c8a0262018-10-03 16:30:44 -07003615sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3616 size_t count = mInputChannelsByToken.count(token);
3617 if (count == 0) {
3618 return nullptr;
3619 }
3620 return mInputChannelsByToken.at(token);
3621}
3622
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003623void InputDispatcher::updateWindowHandlesForDisplayLocked(
3624 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3625 if (inputWindowHandles.empty()) {
3626 // Remove all handles on a display if there are no windows left.
3627 mWindowHandlesByDisplay.erase(displayId);
3628 return;
3629 }
3630
3631 // Since we compare the pointer of input window handles across window updates, we need
3632 // to make sure the handle object for the same window stays unchanged across updates.
3633 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003634 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003635 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003636 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003637 }
3638
3639 std::vector<sp<InputWindowHandle>> newHandles;
3640 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3641 if (!handle->updateInfo()) {
3642 // handle no longer valid
3643 continue;
3644 }
3645
3646 const InputWindowInfo* info = handle->getInfo();
3647 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3648 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3649 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003650 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3651 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3652 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003653 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003654 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003655 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003656 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003657 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003658 }
3659
3660 if (info->displayId != displayId) {
3661 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3662 handle->getName().c_str(), displayId, info->displayId);
3663 continue;
3664 }
3665
Robert Carredd13602020-04-13 17:24:34 -07003666 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3667 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003668 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003669 oldHandle->updateFrom(handle);
3670 newHandles.push_back(oldHandle);
3671 } else {
3672 newHandles.push_back(handle);
3673 }
3674 }
3675
3676 // Insert or replace
3677 mWindowHandlesByDisplay[displayId] = newHandles;
3678}
3679
Arthur Hung72d8dc32020-03-28 00:48:39 +00003680void InputDispatcher::setInputWindows(
3681 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3682 { // acquire lock
3683 std::scoped_lock _l(mLock);
3684 for (auto const& i : handlesPerDisplay) {
3685 setInputWindowsLocked(i.second, i.first);
3686 }
3687 }
3688 // Wake up poll loop since it may need to make new input dispatching choices.
3689 mLooper->wake();
3690}
3691
Arthur Hungb92218b2018-08-14 12:00:21 +08003692/**
3693 * Called from InputManagerService, update window handle list by displayId that can receive input.
3694 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3695 * If set an empty list, remove all handles from the specific display.
3696 * For focused handle, check if need to change and send a cancel event to previous one.
3697 * For removed handle, check if need to send a cancel event if already in touch.
3698 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003699void InputDispatcher::setInputWindowsLocked(
3700 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003701 if (DEBUG_FOCUS) {
3702 std::string windowList;
3703 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3704 windowList += iwh->getName() + " ";
3705 }
3706 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708
Arthur Hung72d8dc32020-03-28 00:48:39 +00003709 // Copy old handles for release if they are no longer present.
3710 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711
Arthur Hung72d8dc32020-03-28 00:48:39 +00003712 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003713
Arthur Hung72d8dc32020-03-28 00:48:39 +00003714 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3715 bool foundHoveredWindow = false;
3716 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3717 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3718 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3719 windowHandle->getInfo()->visible) {
3720 newFocusedWindowHandle = windowHandle;
3721 }
3722 if (windowHandle == mLastHoverWindowHandle) {
3723 foundHoveredWindow = true;
3724 }
3725 }
3726
3727 if (!foundHoveredWindow) {
3728 mLastHoverWindowHandle = nullptr;
3729 }
3730
3731 sp<InputWindowHandle> oldFocusedWindowHandle =
3732 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3733
3734 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3735 if (oldFocusedWindowHandle != nullptr) {
3736 if (DEBUG_FOCUS) {
3737 ALOGD("Focus left window: %s in display %" PRId32,
3738 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003739 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003740 sp<InputChannel> focusedInputChannel =
3741 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3742 if (focusedInputChannel != nullptr) {
3743 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3744 "focus left window");
3745 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3746 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003747 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003748 mFocusedWindowHandlesByDisplay.erase(displayId);
3749 }
3750 if (newFocusedWindowHandle != nullptr) {
3751 if (DEBUG_FOCUS) {
3752 ALOGD("Focus entered window: %s in display %" PRId32,
3753 newFocusedWindowHandle->getName().c_str(), displayId);
3754 }
3755 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3756 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
3758
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 if (mFocusedDisplayId == displayId) {
3760 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003764 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3765 mTouchStatesByDisplay.find(displayId);
3766 if (stateIt != mTouchStatesByDisplay.end()) {
3767 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003768 for (size_t i = 0; i < state.windows.size();) {
3769 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003770 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003771 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772 ALOGD("Touched window was removed: %s in display %" PRId32,
3773 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003774 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003775 sp<InputChannel> touchedInputChannel =
3776 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3777 if (touchedInputChannel != nullptr) {
3778 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3779 "touched window was removed");
3780 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003782 state.windows.erase(state.windows.begin() + i);
3783 } else {
3784 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003787 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003788
Arthur Hung72d8dc32020-03-28 00:48:39 +00003789 // Release information for windows that are no longer present.
3790 // This ensures that unused input channels are released promptly.
3791 // Otherwise, they might stick around until the window handle is destroyed
3792 // which might not happen until the next GC.
3793 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003794 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003795 if (DEBUG_FOCUS) {
3796 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003797 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003798 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003799 }
chaviw291d88a2019-02-14 10:33:58 -08003800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801}
3802
3803void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003804 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003805 if (DEBUG_FOCUS) {
3806 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3807 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003810 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811
Tiger Huang721e26f2018-07-24 22:26:19 +08003812 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3813 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003814
3815 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3816 inputApplicationHandle != oldFocusedApplicationHandle) {
3817 resetNoFocusedWindowTimeoutLocked();
3818 }
3819
Yi Kong9b14ac62018-07-17 13:48:38 -07003820 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003821 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003822 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003824 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003825 oldFocusedApplicationHandle.clear();
3826 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 } // release lock
3829
3830 // Wake up poll loop since it may need to make new input dispatching choices.
3831 mLooper->wake();
3832}
3833
Tiger Huang721e26f2018-07-24 22:26:19 +08003834/**
3835 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3836 * the display not specified.
3837 *
3838 * We track any unreleased events for each window. If a window loses the ability to receive the
3839 * released event, we will send a cancel event to it. So when the focused display is changed, we
3840 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3841 * display. The display-specified events won't be affected.
3842 */
3843void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003844 if (DEBUG_FOCUS) {
3845 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3846 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003847 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003848 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003849
3850 if (mFocusedDisplayId != displayId) {
3851 sp<InputWindowHandle> oldFocusedWindowHandle =
3852 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3853 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003854 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003855 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003856 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857 CancelationOptions
3858 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3859 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003860 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003861 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3862 }
3863 }
3864 mFocusedDisplayId = displayId;
3865
3866 // Sanity check
3867 sp<InputWindowHandle> newFocusedWindowHandle =
3868 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003869 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003870
Tiger Huang721e26f2018-07-24 22:26:19 +08003871 if (newFocusedWindowHandle == nullptr) {
3872 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3873 if (!mFocusedWindowHandlesByDisplay.empty()) {
3874 ALOGE("But another display has a focused window:");
3875 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003876 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003877 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003878 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003879 }
3880 }
3881 }
3882 }
3883
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003884 if (DEBUG_FOCUS) {
3885 logDispatchStateLocked();
3886 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003887 } // release lock
3888
3889 // Wake up poll loop since it may need to make new input dispatching choices.
3890 mLooper->wake();
3891}
3892
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003894 if (DEBUG_FOCUS) {
3895 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
3898 bool changed;
3899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
3902 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3903 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003904 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 }
3906
3907 if (mDispatchEnabled && !enabled) {
3908 resetAndDropEverythingLocked("dispatcher is being disabled");
3909 }
3910
3911 mDispatchEnabled = enabled;
3912 mDispatchFrozen = frozen;
3913 changed = true;
3914 } else {
3915 changed = false;
3916 }
3917
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003918 if (DEBUG_FOCUS) {
3919 logDispatchStateLocked();
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 } // release lock
3922
3923 if (changed) {
3924 // Wake up poll loop since it may need to make new input dispatching choices.
3925 mLooper->wake();
3926 }
3927}
3928
3929void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003930 if (DEBUG_FOCUS) {
3931 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933
3934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
3937 if (mInputFilterEnabled == enabled) {
3938 return;
3939 }
3940
3941 mInputFilterEnabled = enabled;
3942 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3943 } // release lock
3944
3945 // Wake up poll loop since there might be work to do to drop everything.
3946 mLooper->wake();
3947}
3948
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003949void InputDispatcher::setInTouchMode(bool inTouchMode) {
3950 std::scoped_lock lock(mLock);
3951 mInTouchMode = inTouchMode;
3952}
3953
chaviwfbe5d9c2018-12-26 12:23:37 -08003954bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3955 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003956 if (DEBUG_FOCUS) {
3957 ALOGD("Trivial transfer to same window.");
3958 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003959 return true;
3960 }
3961
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003963 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
chaviwfbe5d9c2018-12-26 12:23:37 -08003965 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3966 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003967 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003968 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 return false;
3970 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003971 if (DEBUG_FOCUS) {
3972 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3973 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003976 if (DEBUG_FOCUS) {
3977 ALOGD("Cannot transfer focus because windows are on different displays.");
3978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 return false;
3980 }
3981
3982 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003983 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3984 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003985 for (size_t i = 0; i < state.windows.size(); i++) {
3986 const TouchedWindow& touchedWindow = state.windows[i];
3987 if (touchedWindow.windowHandle == fromWindowHandle) {
3988 int32_t oldTargetFlags = touchedWindow.targetFlags;
3989 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003991 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 int32_t newTargetFlags = oldTargetFlags &
3994 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3995 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003996 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
Jeff Brownf086ddb2014-02-11 14:28:48 -08003998 found = true;
3999 goto Found;
4000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 }
4002 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004005 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004006 if (DEBUG_FOCUS) {
4007 ALOGD("Focus transfer failed because from window did not have focus.");
4008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 return false;
4010 }
4011
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004012 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4013 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004014 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004015 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004016 CancelationOptions
4017 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4018 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004020 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
4022
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004023 if (DEBUG_FOCUS) {
4024 logDispatchStateLocked();
4025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 } // release lock
4027
4028 // Wake up poll loop since it may need to make new input dispatching choices.
4029 mLooper->wake();
4030 return true;
4031}
4032
4033void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004034 if (DEBUG_FOCUS) {
4035 ALOGD("Resetting and dropping all events (%s).", reason);
4036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
4038 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4039 synthesizeCancelationEventsForAllConnectionsLocked(options);
4040
4041 resetKeyRepeatLocked();
4042 releasePendingEventLocked();
4043 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004044 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004046 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004047 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004049 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050}
4051
4052void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004053 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 dumpDispatchStateLocked(dump);
4055
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004056 std::istringstream stream(dump);
4057 std::string line;
4058
4059 while (std::getline(stream, line, '\n')) {
4060 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 }
4062}
4063
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004064void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004065 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4066 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4067 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004068 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
Tiger Huang721e26f2018-07-24 22:26:19 +08004070 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4071 dump += StringPrintf(INDENT "FocusedApplications:\n");
4072 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4073 const int32_t displayId = it.first;
4074 const sp<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004075 const int64_t timeoutMillis = millis(
4076 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004078 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004079 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004082 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004084
4085 if (!mFocusedWindowHandlesByDisplay.empty()) {
4086 dump += StringPrintf(INDENT "FocusedWindows:\n");
4087 for (auto& it : mFocusedWindowHandlesByDisplay) {
4088 const int32_t displayId = it.first;
4089 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4091 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004092 }
4093 } else {
4094 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004097 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004098 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004099 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4100 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004101 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 state.displayId, toString(state.down), toString(state.split),
4103 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004104 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004105 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004106 for (size_t i = 0; i < state.windows.size(); i++) {
4107 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 dump += StringPrintf(INDENT4
4109 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4110 i, touchedWindow.windowHandle->getName().c_str(),
4111 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004112 }
4113 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004114 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004115 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004116 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004117 dump += INDENT3 "Portal windows:\n";
4118 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004119 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4121 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004122 }
4123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
4125 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 }
4128
Arthur Hungb92218b2018-08-14 12:00:21 +08004129 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004131 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004132 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004133 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004134 dump += INDENT2 "Windows:\n";
4135 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004136 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004137 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Arthur Hungb92218b2018-08-14 12:00:21 +08004139 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004141 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004142 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004144 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 i, windowInfo->name.c_str(), windowInfo->displayId,
4146 windowInfo->portalToDisplayId,
4147 toString(windowInfo->paused),
4148 toString(windowInfo->hasFocus),
4149 toString(windowInfo->hasWallpaper),
4150 toString(windowInfo->visible),
4151 toString(windowInfo->canReceiveKeys),
Michael Wright44753b12020-07-08 13:48:11 +01004152 windowInfo->flags.string(InputWindowInfo::flagToString)
4153 .c_str(),
4154 static_cast<int32_t>(windowInfo->type),
4155 windowInfo->frameLeft, windowInfo->frameTop,
4156 windowInfo->frameRight, windowInfo->frameBottom,
4157 windowInfo->globalScaleFactor, windowInfo->windowXScale,
4158 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004159 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004160 dump += StringPrintf(", inputFeatures=%s",
4161 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004162 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4163 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004165 millis(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004166 }
4167 } else {
4168 dump += INDENT2 "Windows: <none>\n";
4169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004172 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
4174
Michael Wright3dd60e22019-03-27 22:06:44 +00004175 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004177 const std::vector<Monitor>& monitors = it.second;
4178 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4179 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 }
4181 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004182 const std::vector<Monitor>& monitors = it.second;
4183 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4184 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004187 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 }
4189
4190 nsecs_t currentTime = now();
4191
4192 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004193 if (!mRecentQueue.empty()) {
4194 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4195 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004198 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 }
4200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203
4204 // Dump event currently being dispatched.
4205 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT "PendingEvent:\n";
4207 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004209 dump += StringPrintf(", age=%" PRId64 "ms\n",
4210 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214
4215 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004216 if (!mInboundQueue.empty()) {
4217 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4218 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004221 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 }
4223 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004227 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004229 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4230 const KeyReplacement& replacement = pair.first;
4231 int32_t newKeyCode = pair.second;
4232 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004234 }
4235 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004236 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004237 }
4238
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004239 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004241 for (const auto& pair : mConnectionsByFd) {
4242 const sp<Connection>& connection = pair.second;
4243 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004244 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004245 pair.first, connection->getInputChannelName().c_str(),
4246 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004247 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004249 if (!connection->outboundQueue.empty()) {
4250 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4251 connection->outboundQueue.size());
4252 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 dump.append(INDENT4);
4254 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004255 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4256 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004258 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 }
4260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004264 if (!connection->waitQueue.empty()) {
4265 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4266 connection->waitQueue.size());
4267 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004268 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004270 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004271 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004273 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004274 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279 }
4280 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004281 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283
4284 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004285 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4286 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 }
4290
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004291 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4293 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4294 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295}
4296
Michael Wright3dd60e22019-03-27 22:06:44 +00004297void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4298 const size_t numMonitors = monitors.size();
4299 for (size_t i = 0; i < numMonitors; i++) {
4300 const Monitor& monitor = monitors[i];
4301 const sp<InputChannel>& channel = monitor.inputChannel;
4302 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4303 dump += "\n";
4304 }
4305}
4306
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004307status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004309 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310#endif
4311
4312 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004313 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004314 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004315 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 return BAD_VALUE;
4319 }
4320
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004321 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
4323 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004324 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004325 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4328 } // release lock
4329
4330 // Wake the looper because some connections have changed.
4331 mLooper->wake();
4332 return OK;
4333}
4334
Michael Wright3dd60e22019-03-27 22:06:44 +00004335status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004337 { // acquire lock
4338 std::scoped_lock _l(mLock);
4339
4340 if (displayId < 0) {
4341 ALOGW("Attempted to register input monitor without a specified display.");
4342 return BAD_VALUE;
4343 }
4344
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004345 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004346 ALOGW("Attempted to register input monitor without an identifying token.");
4347 return BAD_VALUE;
4348 }
4349
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004350 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004351
4352 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004353 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004354 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004355
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 auto& monitorsByDisplay =
4357 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004358 monitorsByDisplay[displayId].emplace_back(inputChannel);
4359
4360 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004361 }
4362 // Wake the looper because some connections have changed.
4363 mLooper->wake();
4364 return OK;
4365}
4366
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4368#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370#endif
4371
4372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
4375 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4376 if (status) {
4377 return status;
4378 }
4379 } // release lock
4380
4381 // Wake the poll loop because removing the connection may have changed the current
4382 // synchronization state.
4383 mLooper->wake();
4384 return OK;
4385}
4386
4387status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004389 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004390 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 return BAD_VALUE;
4394 }
4395
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004396 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004397 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004398
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 if (connection->monitor) {
4400 removeMonitorChannelLocked(inputChannel);
4401 }
4402
4403 mLooper->removeFd(inputChannel->getFd());
4404
4405 nsecs_t currentTime = now();
4406 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4407
4408 connection->status = Connection::STATUS_ZOMBIE;
4409 return OK;
4410}
4411
4412void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004413 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4414 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4415}
4416
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417void InputDispatcher::removeMonitorChannelLocked(
4418 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004419 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004421 std::vector<Monitor>& monitors = it->second;
4422 const size_t numMonitors = monitors.size();
4423 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 if (monitors[i].inputChannel == inputChannel) {
4425 monitors.erase(monitors.begin() + i);
4426 break;
4427 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004428 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004429 if (monitors.empty()) {
4430 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004431 } else {
4432 ++it;
4433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
4435}
4436
Michael Wright3dd60e22019-03-27 22:06:44 +00004437status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4438 { // acquire lock
4439 std::scoped_lock _l(mLock);
4440 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4441
4442 if (!foundDisplayId) {
4443 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4444 return BAD_VALUE;
4445 }
4446 int32_t displayId = foundDisplayId.value();
4447
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004448 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4449 mTouchStatesByDisplay.find(displayId);
4450 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004451 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4452 return BAD_VALUE;
4453 }
4454
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004455 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004456 std::optional<int32_t> foundDeviceId;
4457 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004458 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004459 foundDeviceId = state.deviceId;
4460 }
4461 }
4462 if (!foundDeviceId || !state.down) {
4463 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004465 return BAD_VALUE;
4466 }
4467 int32_t deviceId = foundDeviceId.value();
4468
4469 // Send cancel events to all the input channels we're stealing from.
4470 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004472 options.deviceId = deviceId;
4473 options.displayId = displayId;
4474 for (const TouchedWindow& window : state.windows) {
4475 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004476 if (channel != nullptr) {
4477 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4478 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004479 }
4480 // Then clear the current touch state so we stop dispatching to them as well.
4481 state.filterNonMonitors();
4482 }
4483 return OK;
4484}
4485
Michael Wright3dd60e22019-03-27 22:06:44 +00004486std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4487 const sp<IBinder>& token) {
4488 for (const auto& it : mGestureMonitorsByDisplay) {
4489 const std::vector<Monitor>& monitors = it.second;
4490 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004491 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004492 return it.first;
4493 }
4494 }
4495 }
4496 return std::nullopt;
4497}
4498
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004499sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004500 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004501 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004502 }
4503
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004504 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004505 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004506 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004507 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 }
4509 }
Robert Carr4e670e52018-08-15 13:26:12 -07004510
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004511 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512}
4513
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004515 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004516 removeByValue(mConnectionsByFd, connection);
4517}
4518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4520 const sp<Connection>& connection, uint32_t seq,
4521 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004522 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4523 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 commandEntry->connection = connection;
4525 commandEntry->eventTime = currentTime;
4526 commandEntry->seq = seq;
4527 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004528 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529}
4530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4532 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004534 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004536 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4537 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004539 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540}
4541
chaviw0c06c6e2019-01-09 13:27:07 -08004542void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004543 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004544 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4545 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004546 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4547 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004548 commandEntry->oldToken = oldToken;
4549 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004550 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004551}
4552
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4554 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4555 // is already healthy again. Don't raise ANR in this situation
4556 if (connection->waitQueue.empty()) {
4557 ALOGI("Not raising ANR because the connection %s has recovered",
4558 connection->inputChannel->getName().c_str());
4559 return;
4560 }
4561 /**
4562 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4563 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4564 * has changed. This could cause newer entries to time out before the already dispatched
4565 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4566 * processes the events linearly. So providing information about the oldest entry seems to be
4567 * most useful.
4568 */
4569 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4570 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4571 std::string reason =
4572 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4573 connection->inputChannel->getName().c_str(),
4574 ns2ms(currentWait),
4575 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4578 reason);
4579
4580 std::unique_ptr<CommandEntry> commandEntry =
4581 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4582 commandEntry->inputApplicationHandle = nullptr;
4583 commandEntry->inputChannel = connection->inputChannel;
4584 commandEntry->reason = std::move(reason);
4585 postCommandLocked(std::move(commandEntry));
4586}
4587
4588void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4589 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4590 application->getName().c_str());
4591
4592 updateLastAnrStateLocked(application, reason);
4593
4594 std::unique_ptr<CommandEntry> commandEntry =
4595 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4596 commandEntry->inputApplicationHandle = application;
4597 commandEntry->inputChannel = nullptr;
4598 commandEntry->reason = std::move(reason);
4599 postCommandLocked(std::move(commandEntry));
4600}
4601
4602void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4603 const std::string& reason) {
4604 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4605 updateLastAnrStateLocked(windowLabel, reason);
4606}
4607
4608void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4609 const std::string& reason) {
4610 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4611 updateLastAnrStateLocked(windowLabel, reason);
4612}
4613
4614void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4615 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004617 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 struct tm tm;
4619 localtime_r(&t, &tm);
4620 char timestr[64];
4621 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004622 mLastAnrState.clear();
4623 mLastAnrState += INDENT "ANR:\n";
4624 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4626 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004627 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628}
4629
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004630void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 mLock.unlock();
4632
4633 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4634
4635 mLock.lock();
4636}
4637
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 sp<Connection> connection = commandEntry->connection;
4640
4641 if (connection->status != Connection::STATUS_ZOMBIE) {
4642 mLock.unlock();
4643
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004644 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
4646 mLock.lock();
4647 }
4648}
4649
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004651 sp<IBinder> oldToken = commandEntry->oldToken;
4652 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004653 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004654 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004655 mLock.lock();
4656}
4657
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004658void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004659 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004660 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 mLock.unlock();
4662
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004663 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004664 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665
4666 mLock.lock();
4667
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004668 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004669 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4670 } else {
4671 // stop waking up for events in this connection, it is already not responding
4672 sp<Connection> connection = getConnectionLocked(token);
4673 if (connection == nullptr) {
4674 return;
4675 }
4676 cancelEventsForAnrLocked(connection);
4677 }
4678}
4679
4680void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4681 const sp<IBinder>& connectionToken,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004682 std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004683 sp<Connection> connection = getConnectionLocked(connectionToken);
4684 if (connection == nullptr) {
4685 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4686 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004687 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688 mAwaitedFocusedApplication = application;
4689 } else {
4690 // It's also possible that the connection already disappeared. No action necessary.
4691 }
4692 return;
4693 }
4694
4695 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004696 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697
4698 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004699 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 for (DispatchEntry* entry : connection->waitQueue) {
4701 if (newTimeout >= entry->timeoutTime) {
4702 // Already removed old entries when connection was marked unresponsive
4703 entry->timeoutTime = newTimeout;
4704 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4705 }
4706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707}
4708
4709void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4710 CommandEntry* commandEntry) {
4711 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004712 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713
4714 mLock.unlock();
4715
Michael Wright2b3c3302018-03-02 17:19:13 +00004716 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004717 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004718 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004719 : nullptr;
4720 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004721 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4722 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
4726 mLock.lock();
4727
4728 if (delay < 0) {
4729 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4730 } else if (!delay) {
4731 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4732 } else {
4733 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4734 entry->interceptKeyWakeupTime = now() + delay;
4735 }
4736 entry->release();
4737}
4738
chaviwfd6d3512019-03-25 13:23:49 -07004739void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4740 mLock.unlock();
4741 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4742 mLock.lock();
4743}
4744
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745/**
4746 * Connection is responsive if it has no events in the waitQueue that are older than the
4747 * current time.
4748 */
4749static bool isConnectionResponsive(const Connection& connection) {
4750 const nsecs_t currentTime = now();
4751 for (const DispatchEntry* entry : connection.waitQueue) {
4752 if (entry->timeoutTime < currentTime) {
4753 return false;
4754 }
4755 }
4756 return true;
4757}
4758
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004759void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004761 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004763 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764
4765 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004766 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004767 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004768 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004770 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004771 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004772 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004773 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4774 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004775 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004776 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004777
4778 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004779 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004780 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4781 restartEvent =
4782 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004783 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004784 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4785 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4786 handled);
4787 } else {
4788 restartEvent = false;
4789 }
4790
4791 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004792 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004793 // contents of the wait queue to have been drained, so we need to double-check
4794 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004795 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4796 if (dispatchEntryIt != connection->waitQueue.end()) {
4797 dispatchEntry = *dispatchEntryIt;
4798 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799 mAnrTracker.erase(dispatchEntry->timeoutTime,
4800 connection->inputChannel->getConnectionToken());
4801 if (!connection->responsive) {
4802 connection->responsive = isConnectionResponsive(*connection);
4803 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004804 traceWaitQueueLength(connection);
4805 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004806 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004807 traceOutboundQueueLength(connection);
4808 } else {
4809 releaseDispatchEntry(dispatchEntry);
4810 }
4811 }
4812
4813 // Start the next dispatch cycle for this connection.
4814 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815}
4816
4817bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 DispatchEntry* dispatchEntry,
4819 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004820 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004821 if (!handled) {
4822 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004823 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004824 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004825 return false;
4826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004828 // Get the fallback key state.
4829 // Clear it out after dispatching the UP.
4830 int32_t originalKeyCode = keyEntry->keyCode;
4831 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4832 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4833 connection->inputState.removeFallbackKey(originalKeyCode);
4834 }
4835
4836 if (handled || !dispatchEntry->hasForegroundTarget()) {
4837 // If the application handles the original key for which we previously
4838 // generated a fallback or if the window is not a foreground window,
4839 // then cancel the associated fallback key, if any.
4840 if (fallbackKeyCode != -1) {
4841 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004843 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4845 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4846 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004848 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004849 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
4851 mLock.unlock();
4852
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004853 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004854 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
4856 mLock.lock();
4857
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004858 // Cancel the fallback key.
4859 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004861 "application handled the original non-fallback key "
4862 "or is no longer a foreground target, "
4863 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 options.keyCode = fallbackKeyCode;
4865 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004867 connection->inputState.removeFallbackKey(originalKeyCode);
4868 }
4869 } else {
4870 // If the application did not handle a non-fallback key, first check
4871 // that we are in a good state to perform unhandled key event processing
4872 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004873 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004874 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004876 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004877 "since this is not an initial down. "
4878 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4879 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004881 return false;
4882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884 // Dispatch the unhandled key to the policy.
4885#if DEBUG_OUTBOUND_EVENT_DETAILS
4886 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004887 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4888 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004889#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004890 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004891
4892 mLock.unlock();
4893
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004894 bool fallback =
4895 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4896 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004897
4898 mLock.lock();
4899
4900 if (connection->status != Connection::STATUS_NORMAL) {
4901 connection->inputState.removeFallbackKey(originalKeyCode);
4902 return false;
4903 }
4904
4905 // Latch the fallback keycode for this key on an initial down.
4906 // The fallback keycode cannot change at any other point in the lifecycle.
4907 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004909 fallbackKeyCode = event.getKeyCode();
4910 } else {
4911 fallbackKeyCode = AKEYCODE_UNKNOWN;
4912 }
4913 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4914 }
4915
4916 ALOG_ASSERT(fallbackKeyCode != -1);
4917
4918 // Cancel the fallback key if the policy decides not to send it anymore.
4919 // We will continue to dispatch the key to the policy but we will no
4920 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004921 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4922 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004923#if DEBUG_OUTBOUND_EVENT_DETAILS
4924 if (fallback) {
4925 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004926 "as a fallback for %d, but on the DOWN it had requested "
4927 "to send %d instead. Fallback canceled.",
4928 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004929 } else {
4930 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004931 "but on the DOWN it had requested to send %d. "
4932 "Fallback canceled.",
4933 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 }
4935#endif
4936
4937 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4938 "canceling fallback, policy no longer desires it");
4939 options.keyCode = fallbackKeyCode;
4940 synthesizeCancelationEventsForConnectionLocked(connection, options);
4941
4942 fallback = false;
4943 fallbackKeyCode = AKEYCODE_UNKNOWN;
4944 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004946 }
4947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948
4949#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004950 {
4951 std::string msg;
4952 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4953 connection->inputState.getFallbackKeys();
4954 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004955 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004957 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004958 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004959 }
4960#endif
4961
4962 if (fallback) {
4963 // Restart the dispatch cycle using the fallback key.
4964 keyEntry->eventTime = event.getEventTime();
4965 keyEntry->deviceId = event.getDeviceId();
4966 keyEntry->source = event.getSource();
4967 keyEntry->displayId = event.getDisplayId();
4968 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4969 keyEntry->keyCode = fallbackKeyCode;
4970 keyEntry->scanCode = event.getScanCode();
4971 keyEntry->metaState = event.getMetaState();
4972 keyEntry->repeatCount = event.getRepeatCount();
4973 keyEntry->downTime = event.getDownTime();
4974 keyEntry->syntheticRepeat = false;
4975
4976#if DEBUG_OUTBOUND_EVENT_DETAILS
4977 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4979 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004980#endif
4981 return true; // restart the event
4982 } else {
4983#if DEBUG_OUTBOUND_EVENT_DETAILS
4984 ALOGD("Unhandled key event: No fallback key.");
4985#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004986
4987 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004988 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 }
4990 }
4991 return false;
4992}
4993
4994bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 DispatchEntry* dispatchEntry,
4996 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 return false;
4998}
4999
5000void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5001 mLock.unlock();
5002
5003 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5004
5005 mLock.lock();
5006}
5007
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005008KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5009 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005010 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005011 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5012 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005013 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014}
5015
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005016void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5017 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 // TODO Write some statistics about how long we spend waiting.
5019}
5020
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005021/**
5022 * Report the touch event latency to the statsd server.
5023 * Input events are reported for statistics if:
5024 * - This is a touchscreen event
5025 * - InputFilter is not enabled
5026 * - Event is not injected or synthesized
5027 *
5028 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5029 * from getting aggregated with the "old" data.
5030 */
5031void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5032 REQUIRES(mLock) {
5033 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5034 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5035 if (!reportForStatistics) {
5036 return;
5037 }
5038
5039 if (mTouchStatistics.shouldReport()) {
5040 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5041 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5042 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5043 mTouchStatistics.reset();
5044 }
5045 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5046 mTouchStatistics.addValue(latencyMicros);
5047}
5048
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049void InputDispatcher::traceInboundQueueLengthLocked() {
5050 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005051 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053}
5054
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005055void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 if (ATRACE_ENABLED()) {
5057 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005058 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005059 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061}
5062
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005063void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 if (ATRACE_ENABLED()) {
5065 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005066 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005067 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
5069}
5070
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005072 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005074 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 dumpDispatchStateLocked(dump);
5076
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005077 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005078 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005079 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081}
5082
5083void InputDispatcher::monitor() {
5084 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005085 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005087 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088}
5089
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005090/**
5091 * Wake up the dispatcher and wait until it processes all events and commands.
5092 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5093 * this method can be safely called from any thread, as long as you've ensured that
5094 * the work you are interested in completing has already been queued.
5095 */
5096bool InputDispatcher::waitForIdle() {
5097 /**
5098 * Timeout should represent the longest possible time that a device might spend processing
5099 * events and commands.
5100 */
5101 constexpr std::chrono::duration TIMEOUT = 100ms;
5102 std::unique_lock lock(mLock);
5103 mLooper->wake();
5104 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5105 return result == std::cv_status::no_timeout;
5106}
5107
Garfield Tane84e6f92019-08-29 17:28:41 -07005108} // namespace android::inputdispatcher