blob: 70491b99dc9276a95c0786f4eb64aeaccff32e08 [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
Garfield Tan400128f2020-09-22 21:53:55 +000031// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
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>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.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 Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
Vishnu Nair958da932020-08-21 17:12:37 -0700255/**
256 * Find the entry in std::unordered_map by key and return the value as an optional.
257 */
258template <typename K, typename V>
259static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
260 auto it = map.find(key);
261 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
262}
263
chaviwaf87b3e2019-10-01 16:59:28 -0700264static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
265 if (first == second) {
266 return true;
267 }
268
269 if (first == nullptr || second == nullptr) {
270 return false;
271 }
272
273 return first->getToken() == second->getToken();
274}
275
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800276static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
277 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
278}
279
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000280static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
281 EventEntry* eventEntry,
282 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700283 if (inputTarget.useDefaultPointerTransform()) {
284 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000285 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700286 inputTargetFlags, transform,
287 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000288 }
289
290 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
291 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
292
293 PointerCoords pointerCoords[motionEntry.pointerCount];
294
295 // Use the first pointer information to normalize all other pointers. This could be any pointer
296 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 // uses the transform for the normalized pointer.
298 const ui::Transform& firstPointerTransform =
299 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
300 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000301
302 // Iterate through all pointers in the event to normalize against the first.
303 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
304 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
305 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700306 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 // First, apply the current pointer's transform to update the coordinates into
310 // window space.
311 pointerCoords[pointerIndex].transform(currTransform);
312 // Next, apply the inverse transform of the normalized coordinates so the
313 // current coordinates are transformed into the normalized coordinate space.
314 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 }
316
317 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800318 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
320 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
321 motionEntry.metaState, motionEntry.buttonState,
322 motionEntry.classification, motionEntry.edgeFlags,
323 motionEntry.xPrecision, motionEntry.yPrecision,
324 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
325 motionEntry.downTime, motionEntry.pointerCount,
326 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
327 0 /* yOffset */);
328
329 if (motionEntry.injectionState) {
330 combinedMotionEntry->injectionState = motionEntry.injectionState;
331 combinedMotionEntry->injectionState->refCount += 1;
332 }
333
334 std::unique_ptr<DispatchEntry> dispatchEntry =
335 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 inputTargetFlags, firstPointerTransform,
337 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 combinedMotionEntry->release();
339 return dispatchEntry;
340}
341
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700342static void addGestureMonitors(const std::vector<Monitor>& monitors,
343 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
344 float yOffset = 0) {
345 if (monitors.empty()) {
346 return;
347 }
348 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
349 for (const Monitor& monitor : monitors) {
350 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
351 }
352}
353
Vishnu Nair958da932020-08-21 17:12:37 -0700354const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
355 switch (result) {
356 case InputDispatcher::FocusResult::OK:
357 return "Ok";
358 case InputDispatcher::FocusResult::NO_WINDOW:
359 return "Window not found";
360 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
361 return "Window not focusable";
362 case InputDispatcher::FocusResult::NOT_VISIBLE:
363 return "Window not visible";
364 }
365}
366
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500367template <typename T>
368static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
369 if (lhs == nullptr && rhs == nullptr) {
370 return true;
371 }
372 if (lhs == nullptr || rhs == nullptr) {
373 return false;
374 }
375 return *lhs == *rhs;
376}
377
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378// --- InputDispatcher ---
379
Garfield Tan00f511d2019-06-12 16:55:40 -0700380InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
381 : mPolicy(policy),
382 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700383 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800384 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700385 mAppSwitchSawKeyDown(false),
386 mAppSwitchDueTime(LONG_LONG_MAX),
387 mNextUnblockedEvent(nullptr),
388 mDispatchEnabled(false),
389 mDispatchFrozen(false),
390 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800391 // mInTouchMode will be initialized by the WindowManager to the default device config.
392 // To avoid leaking stack in case that call never comes, and for tests,
393 // initialize it here anyways.
394 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700395 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800397 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800398
Yi Kong9b14ac62018-07-17 13:48:38 -0700399 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400
401 policy->getDispatcherConfiguration(&mConfig);
402}
403
404InputDispatcher::~InputDispatcher() {
405 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800406 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407
408 resetKeyRepeatLocked();
409 releasePendingEventLocked();
410 drainInboundQueueLocked();
411 }
412
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700413 while (!mConnectionsByFd.empty()) {
414 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan400128f2020-09-22 21:53:55 +0000415 unregisterInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416 }
417}
418
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700419status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700420 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700421 return ALREADY_EXISTS;
422 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700423 mThread = std::make_unique<InputThread>(
424 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
425 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700426}
427
428status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700429 if (mThread && mThread->isCallingThread()) {
430 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700431 return INVALID_OPERATION;
432 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 mThread.reset();
434 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700435}
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437void InputDispatcher::dispatchOnce() {
438 nsecs_t nextWakeupTime = LONG_LONG_MAX;
439 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800440 std::scoped_lock _l(mLock);
441 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442
443 // Run a dispatch loop if there are no pending commands.
444 // The dispatch loop might enqueue commands to run afterwards.
445 if (!haveCommandsLocked()) {
446 dispatchOnceInnerLocked(&nextWakeupTime);
447 }
448
449 // Run all pending commands if there are any.
450 // If any commands were run then force the next poll to wake up immediately.
451 if (runCommandsLockedInterruptible()) {
452 nextWakeupTime = LONG_LONG_MIN;
453 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800454
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700455 // If we are still waiting for ack on some events,
456 // we might have to wake up earlier to check if an app is anr'ing.
457 const nsecs_t nextAnrCheck = processAnrsLocked();
458 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
459
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800460 // We are about to enter an infinitely long sleep, because we have no commands or
461 // pending or queued events
462 if (nextWakeupTime == LONG_LONG_MAX) {
463 mDispatcherEnteredIdle.notify_all();
464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 } // release lock
466
467 // Wait for callback or timeout or wake. (make sure we round up, not down)
468 nsecs_t currentTime = now();
469 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
470 mLooper->pollOnce(timeoutMillis);
471}
472
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700473/**
474 * Check if any of the connections' wait queues have events that are too old.
475 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
476 * Return the time at which we should wake up next.
477 */
478nsecs_t InputDispatcher::processAnrsLocked() {
479 const nsecs_t currentTime = now();
480 nsecs_t nextAnrCheck = LONG_LONG_MAX;
481 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
482 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
483 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
484 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700485 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700486 return LONG_LONG_MIN;
487 } else {
488 // Keep waiting
489 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
490 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
491 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
492 }
493 }
494
495 // Check if any connection ANRs are due
496 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
497 if (currentTime < nextAnrCheck) { // most likely scenario
498 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
499 }
500
501 // If we reached here, we have an unresponsive connection.
502 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
503 if (connection == nullptr) {
504 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
505 return nextAnrCheck;
506 }
507 connection->responsive = false;
508 // Stop waking up for this unresponsive connection
509 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
510 onAnrLocked(connection);
511 return LONG_LONG_MIN;
512}
513
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500514std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700515 sp<InputWindowHandle> window = getWindowHandleLocked(token);
516 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500517 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700518 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500519 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700520}
521
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
523 nsecs_t currentTime = now();
524
Jeff Browndc5992e2014-04-11 01:27:26 -0700525 // Reset the key repeat timer whenever normal dispatch is suspended while the
526 // device is in a non-interactive state. This is to ensure that we abort a key
527 // repeat if the device is just coming out of sleep.
528 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 resetKeyRepeatLocked();
530 }
531
532 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
533 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100534 if (DEBUG_FOCUS) {
535 ALOGD("Dispatch frozen. Waiting some more.");
536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 return;
538 }
539
540 // Optimize latency of app switches.
541 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
542 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
543 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
544 if (mAppSwitchDueTime < *nextWakeupTime) {
545 *nextWakeupTime = mAppSwitchDueTime;
546 }
547
548 // Ready to start a new event.
549 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700550 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700551 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 if (isAppSwitchDue) {
553 // The inbound queue is empty so the app switch key we were waiting
554 // for will never arrive. Stop waiting for it.
555 resetPendingAppSwitchLocked(false);
556 isAppSwitchDue = false;
557 }
558
559 // Synthesize a key repeat if appropriate.
560 if (mKeyRepeatState.lastKeyEntry) {
561 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
562 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
563 } else {
564 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
565 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
566 }
567 }
568 }
569
570 // Nothing to do if there is no pending event.
571 if (!mPendingEvent) {
572 return;
573 }
574 } else {
575 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700576 mPendingEvent = mInboundQueue.front();
577 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 traceInboundQueueLengthLocked();
579 }
580
581 // Poke user activity for this event.
582 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700583 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 }
586
587 // Now we have an event to dispatch.
588 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700589 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700591 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700593 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700595 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597
598 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700599 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
601
602 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700603 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700604 ConfigurationChangedEntry* typedEntry =
605 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
606 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700607 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700608 break;
609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700611 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700612 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
613 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 break;
616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100618 case EventEntry::Type::FOCUS: {
619 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
620 dispatchFocusLocked(currentTime, typedEntry);
621 done = true;
622 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
623 break;
624 }
625
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700626 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700627 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
628 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700629 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 resetPendingAppSwitchLocked(true);
631 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700632 } else if (dropReason == DropReason::NOT_DROPPED) {
633 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700634 }
635 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700636 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700639 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
640 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 }
642 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
643 break;
644 }
645
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700646 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700647 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
649 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700651 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700652 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700654 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
655 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700656 }
657 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
658 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
661
662 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700664 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
Michael Wright3a981722015-06-10 15:26:13 +0100666 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667
668 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
671}
672
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700673/**
674 * Return true if the events preceding this incoming motion event should be dropped
675 * Return false otherwise (the default behaviour)
676 */
677bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700679 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700680
681 // Optimize case where the current application is unresponsive and the user
682 // decides to touch a window in a different application.
683 // If the application takes too long to catch up then we drop all events preceding
684 // the touch into the other window.
685 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700686 int32_t displayId = motionEntry.displayId;
687 int32_t x = static_cast<int32_t>(
688 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
689 int32_t y = static_cast<int32_t>(
690 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
691 sp<InputWindowHandle> touchedWindowHandle =
692 findTouchedWindowAtLocked(displayId, x, y, nullptr);
693 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 touchedWindowHandle->getApplicationToken() !=
695 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700696 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700697 ALOGI("Pruning input queue because user touched a different application while waiting "
698 "for %s",
699 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700700 return true;
701 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700702
703 // Alternatively, maybe there's a gesture monitor that could handle this event
704 std::vector<TouchedMonitor> gestureMonitors =
705 findTouchedGestureMonitorsLocked(displayId, {});
706 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
707 sp<Connection> connection =
708 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000709 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710 // This monitor could take more input. Drop all events preceding this
711 // event, so that gesture monitor could get a chance to receive the stream
712 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
713 "responsive gesture monitor that may handle the event",
714 mAwaitedFocusedApplication->getName().c_str());
715 return true;
716 }
717 }
718 }
719
720 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
721 // yet been processed by some connections, the dispatcher will wait for these motion
722 // events to be processed before dispatching the key event. This is because these motion events
723 // may cause a new window to be launched, which the user might expect to receive focus.
724 // To prevent waiting forever for such events, just send the key to the currently focused window
725 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
726 ALOGD("Received a new pointer down event, stop waiting for events to process and "
727 "just send the pending key event to the focused window.");
728 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700729 }
730 return false;
731}
732
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700734 bool needWake = mInboundQueue.empty();
735 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 traceInboundQueueLengthLocked();
737
738 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700739 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 // Optimize app switch latency.
741 // If the application takes too long to catch up then we drop all events preceding
742 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700743 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700744 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700745 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700747 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700748 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700752 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 mAppSwitchSawKeyDown = false;
754 needWake = true;
755 }
756 }
757 }
758 break;
759 }
760
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700761 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700762 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
763 mNextUnblockedEvent = entry;
764 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100768 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700769 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
770 break;
771 }
772 case EventEntry::Type::CONFIGURATION_CHANGED:
773 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700774 // nothing to do
775 break;
776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778
779 return needWake;
780}
781
782void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
783 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700784 mRecentQueue.push_back(entry);
785 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
786 mRecentQueue.front()->release();
787 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789}
790
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700792 int32_t y, TouchState* touchState,
793 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700795 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
796 LOG_ALWAYS_FATAL(
797 "Must provide a valid touch state if adding portal windows or outside targets");
798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700800 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800801 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 const InputWindowInfo* windowInfo = windowHandle->getInfo();
803 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100804 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
806 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100807 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
808 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
809 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800811 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 if (portalToDisplayId != ADISPLAY_ID_NONE &&
813 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800814 if (addPortalWindows) {
815 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700816 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800817 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700818 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 // Found window.
822 return windowHandle;
823 }
824 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800825
Michael Wright44753b12020-07-08 13:48:11 +0100826 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700827 touchState->addOrUpdateWindow(windowHandle,
828 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
829 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 }
833 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700834 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835}
836
Garfield Tane84e6f92019-08-29 17:28:41 -0700837std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700838 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000839 std::vector<TouchedMonitor> touchedMonitors;
840
841 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
842 addGestureMonitors(monitors, touchedMonitors);
843 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
844 const InputWindowInfo* windowInfo = portalWindow->getInfo();
845 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
847 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000848 }
849 return touchedMonitors;
850}
851
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700852void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 const char* reason;
854 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700855 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 reason = "inbound event was dropped because the policy consumed it";
860 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 case DropReason::DISABLED:
862 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 ALOGI("Dropped event because input dispatch is disabled.");
864 }
865 reason = "inbound event was dropped because input dispatch is disabled";
866 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 ALOGI("Dropped event because of pending overdue app switch.");
869 reason = "inbound event was dropped because of pending overdue app switch";
870 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 ALOGI("Dropped event because the current application is not responding and the user "
873 "has started interacting with a different application.");
874 reason = "inbound event was dropped because the current application is not responding "
875 "and the user has started interacting with a different application";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 ALOGI("Dropped event because it is stale.");
879 reason = "inbound event was dropped because it is stale";
880 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 case DropReason::NOT_DROPPED: {
882 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700887 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700888 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
890 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700893 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
895 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
897 synthesizeCancelationEventsForAllConnectionsLocked(options);
898 } else {
899 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
900 synthesizeCancelationEventsForAllConnectionsLocked(options);
901 }
902 break;
903 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100904 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::CONFIGURATION_CHANGED:
906 case EventEntry::Type::DEVICE_RESET: {
907 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
908 break;
909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911}
912
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800913static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
915 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916}
917
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700918bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
919 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
920 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
921 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922}
923
924bool InputDispatcher::isAppSwitchPendingLocked() {
925 return mAppSwitchDueTime != LONG_LONG_MAX;
926}
927
928void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
929 mAppSwitchDueTime = LONG_LONG_MAX;
930
931#if DEBUG_APP_SWITCH
932 if (handled) {
933 ALOGD("App switch has arrived.");
934 } else {
935 ALOGD("App switch was abandoned.");
936 }
937#endif
938}
939
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700941 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942}
943
944bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700945 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 return false;
947 }
948
949 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700950 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700951 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700953 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954
955 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700956 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 return true;
958}
959
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700960void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
961 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962}
963
964void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 while (!mInboundQueue.empty()) {
966 EventEntry* entry = mInboundQueue.front();
967 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 releaseInboundEventLocked(entry);
969 }
970 traceInboundQueueLengthLocked();
971}
972
973void InputDispatcher::releasePendingEventLocked() {
974 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700976 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 }
978}
979
980void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
981 InjectionState* injectionState = entry->injectionState;
982 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
983#if DEBUG_DISPATCH_CYCLE
984 ALOGD("Injected inbound event was dropped.");
985#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800986 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 }
988 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700989 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991 addRecentEventLocked(entry);
992 entry->release();
993}
994
995void InputDispatcher::resetKeyRepeatLocked() {
996 if (mKeyRepeatState.lastKeyEntry) {
997 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700998 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000}
1001
Garfield Tane84e6f92019-08-29 17:28:41 -07001002KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1004
1005 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001006 uint32_t policyFlags = entry->policyFlags &
1007 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (entry->refCount == 1) {
1009 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001010 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 entry->eventTime = currentTime;
1012 entry->policyFlags = policyFlags;
1013 entry->repeatCount += 1;
1014 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001016 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001017 entry->displayId, policyFlags, entry->action, entry->flags,
1018 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020
1021 mKeyRepeatState.lastKeyEntry = newEntry;
1022 entry->release();
1023
1024 entry = newEntry;
1025 }
1026 entry->syntheticRepeat = true;
1027
1028 // Increment reference count since we keep a reference to the event in
1029 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1030 entry->refCount += 1;
1031
1032 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1033 return entry;
1034}
1035
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1037 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001039 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040#endif
1041
1042 // Reset key repeating in case a keyboard device was added or removed or something.
1043 resetKeyRepeatLocked();
1044
1045 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001046 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1047 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001049 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 return true;
1051}
1052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001055 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057#endif
1058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 options.deviceId = entry->deviceId;
1061 synthesizeCancelationEventsForAllConnectionsLocked(options);
1062 return true;
1063}
1064
Vishnu Nairad321cd2020-08-20 16:40:21 -07001065void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001066 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001067 if (mPendingEvent != nullptr) {
1068 // Move the pending event to the front of the queue. This will give the chance
1069 // for the pending event to get dispatched to the newly focused window
1070 mInboundQueue.push_front(mPendingEvent);
1071 mPendingEvent = nullptr;
1072 }
1073
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001074 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001075 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001076
1077 // This event should go to the front of the queue, but behind all other focus events
1078 // Find the last focus event, and insert right after it
1079 std::deque<EventEntry*>::reverse_iterator it =
1080 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1081 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1082
1083 // Maintain the order of focus events. Insert the entry after all other focus events.
1084 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085}
1086
1087void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001088 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 if (channel == nullptr) {
1090 return; // Window has gone away
1091 }
1092 InputTarget target;
1093 target.inputChannel = channel;
1094 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1095 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001096 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1097 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001098 std::string reason = std::string("reason=").append(entry->reason);
1099 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100 dispatchEventLocked(currentTime, entry, {target});
1101}
1102
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 if (!entry->dispatchInProgress) {
1107 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1108 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1109 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1110 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001111 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 // We have seen two identical key downs in a row which indicates that the device
1113 // driver is automatically generating key repeats itself. We take note of the
1114 // repeat here, but we disable our own next key repeat timer since it is clear that
1115 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001116 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1117 // Make sure we don't get key down from a different device. If a different
1118 // device Id has same key pressed down, the new device Id will replace the
1119 // current one to hold the key repeat with repeat count reset.
1120 // In the future when got a KEY_UP on the device id, drop it and do not
1121 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1123 resetKeyRepeatLocked();
1124 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1125 } else {
1126 // Not a repeat. Save key down state in case we do see a repeat later.
1127 resetKeyRepeatLocked();
1128 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1129 }
1130 mKeyRepeatState.lastKeyEntry = entry;
1131 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001132 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1133 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1134 // The stale device releases the key, reset staleDeviceId.
1135#if DEBUG_INBOUND_EVENT_DETAILS
1136 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1137#endif
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);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001170 sp<IBinder> focusedWindowToken =
1171 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1172 if (focusedWindowToken != nullptr) {
1173 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
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
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001349 updateInteractionTokensLocked(*eventEntry, inputTargets);
1350
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001355 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001356 sp<Connection> connection =
1357 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001358 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001359 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001361 if (DEBUG_FOCUS) {
1362 ALOGD("Dropping event delivery to target with channel '%s' because it "
1363 "is no longer registered with the input dispatcher.",
1364 inputTarget.inputChannel->getName().c_str());
1365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
1368}
1369
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001370void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1371 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1372 // If the policy decides to close the app, we will get a channel removal event via
1373 // unregisterInputChannel, and will clean up the connection that way. We are already not
1374 // sending new pointers to the connection when it blocked, but focused events will continue to
1375 // pile up.
1376 ALOGW("Canceling events for %s because it is unresponsive",
1377 connection->inputChannel->getName().c_str());
1378 if (connection->status == Connection::STATUS_NORMAL) {
1379 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1380 "application not responding");
1381 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383}
1384
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001385void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001386 if (DEBUG_FOCUS) {
1387 ALOGD("Resetting ANR timeouts.");
1388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389
1390 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001391 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001392 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393}
1394
Tiger Huang721e26f2018-07-24 22:26:19 +08001395/**
1396 * Get the display id that the given event should go to. If this event specifies a valid display id,
1397 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1398 * Focused display is the display that the user most recently interacted with.
1399 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001401 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001403 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1405 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001406 break;
1407 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1410 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 break;
1412 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001413 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001414 case EventEntry::Type::CONFIGURATION_CHANGED:
1415 case EventEntry::Type::DEVICE_RESET: {
1416 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 return ADISPLAY_ID_NONE;
1418 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001419 }
1420 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1421}
1422
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001423bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1424 const char* focusedWindowName) {
1425 if (mAnrTracker.empty()) {
1426 // already processed all events that we waited for
1427 mKeyIsWaitingForEventsTimeout = std::nullopt;
1428 return false;
1429 }
1430
1431 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1432 // Start the timer
1433 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1434 "focus to change",
1435 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001436 mKeyIsWaitingForEventsTimeout = currentTime +
1437 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1438 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001439 return true;
1440 }
1441
1442 // We still have pending events, and already started the timer
1443 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1444 return true; // Still waiting
1445 }
1446
1447 // Waited too long, and some connection still hasn't processed all motions
1448 // Just send the key to the focused window
1449 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1450 focusedWindowName);
1451 mKeyIsWaitingForEventsTimeout = std::nullopt;
1452 return false;
1453}
1454
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001456 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 std::vector<InputTarget>& inputTargets,
1458 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001459 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460
Tiger Huang721e26f2018-07-24 22:26:19 +08001461 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001462 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001463 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001464 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1465
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 // If there is no currently focused window and no focused application
1467 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001468 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1469 ALOGI("Dropping %s event because there is no focused window or focused application in "
1470 "display %" PRId32 ".",
1471 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001472 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 }
1474
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001475 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1476 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1477 // start interacting with another application via touch (app switch). This code can be removed
1478 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1479 // an app is expected to have a focused window.
1480 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1481 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1482 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001483 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1484 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1485 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001486 mAwaitedFocusedApplication = focusedApplicationHandle;
1487 ALOGW("Waiting because no window has focus but %s may eventually add a "
1488 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001489 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001490 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1491 return INPUT_EVENT_INJECTION_PENDING;
1492 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1493 // Already raised ANR. Drop the event
1494 ALOGE("Dropping %s event because there is no focused window",
1495 EventEntry::typeToString(entry.type));
1496 return INPUT_EVENT_INJECTION_FAILED;
1497 } else {
1498 // Still waiting for the focused window
1499 return INPUT_EVENT_INJECTION_PENDING;
1500 }
1501 }
1502
1503 // we have a valid, non-null focused window
1504 resetNoFocusedWindowTimeoutLocked();
1505
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001507 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001508 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001511 if (focusedWindowHandle->getInfo()->paused) {
1512 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1513 return INPUT_EVENT_INJECTION_PENDING;
1514 }
1515
1516 // If the event is a key event, then we must wait for all previous events to
1517 // complete before delivering it because previous events may have the
1518 // side-effect of transferring focus to a different window and we want to
1519 // ensure that the following keys are sent to the new window.
1520 //
1521 // Suppose the user touches a button in a window then immediately presses "A".
1522 // If the button causes a pop-up window to appear then we want to ensure that
1523 // the "A" key is delivered to the new pop-up window. This is because users
1524 // often anticipate pending UI changes when typing on a keyboard.
1525 // To obtain this behavior, we must serialize key events with respect to all
1526 // prior input events.
1527 if (entry.type == EventEntry::Type::KEY) {
1528 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1529 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1530 return INPUT_EVENT_INJECTION_PENDING;
1531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
1533
1534 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001535 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001536 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1537 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
1539 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001540 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541}
1542
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001543/**
1544 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1545 * that are currently unresponsive.
1546 */
1547std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1548 const std::vector<TouchedMonitor>& monitors) const {
1549 std::vector<TouchedMonitor> responsiveMonitors;
1550 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1551 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1552 sp<Connection> connection = getConnectionLocked(
1553 monitor.monitor.inputChannel->getConnectionToken());
1554 if (connection == nullptr) {
1555 ALOGE("Could not find connection for monitor %s",
1556 monitor.monitor.inputChannel->getName().c_str());
1557 return false;
1558 }
1559 if (!connection->responsive) {
1560 ALOGW("Unresponsive monitor %s will not get the new gesture",
1561 connection->inputChannel->getName().c_str());
1562 return false;
1563 }
1564 return true;
1565 });
1566 return responsiveMonitors;
1567}
1568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571 std::vector<InputTarget>& inputTargets,
1572 nsecs_t* nextWakeupTime,
1573 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001574 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 enum InjectionPermission {
1576 INJECTION_PERMISSION_UNKNOWN,
1577 INJECTION_PERMISSION_GRANTED,
1578 INJECTION_PERMISSION_DENIED
1579 };
1580
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 // For security reasons, we defer updating the touch state until we are sure that
1582 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 int32_t displayId = entry.displayId;
1584 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1586
1587 // Update the touch state as needed based on the properties of the touch event.
1588 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1589 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001590 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1591 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001593 // Copy current touch state into tempTouchState.
1594 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1595 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001596 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001597 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001598 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1599 mTouchStatesByDisplay.find(displayId);
1600 if (oldStateIt != mTouchStatesByDisplay.end()) {
1601 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001602 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001603 }
1604
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001605 bool isSplit = tempTouchState.split;
1606 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1607 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1608 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001609 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1610 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1611 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1612 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1613 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 bool wrongDevice = false;
1616 if (newGesture) {
1617 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001618 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001619 ALOGI("Dropping event because a pointer for a different device is already down "
1620 "in display %" PRId32,
1621 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001622 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1624 switchedDevice = false;
1625 wrongDevice = true;
1626 goto Failed;
1627 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001628 tempTouchState.reset();
1629 tempTouchState.down = down;
1630 tempTouchState.deviceId = entry.deviceId;
1631 tempTouchState.source = entry.source;
1632 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001634 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001635 ALOGI("Dropping move event because a pointer for a different device is already active "
1636 "in display %" PRId32,
1637 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001638 // TODO: test multiple simultaneous input streams.
1639 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1640 switchedDevice = false;
1641 wrongDevice = true;
1642 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 }
1644
1645 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1646 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1647
Garfield Tan00f511d2019-06-12 16:55:40 -07001648 int32_t x;
1649 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001651 // Always dispatch mouse events to cursor position.
1652 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 x = int32_t(entry.xCursorPosition);
1654 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001655 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001656 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1657 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001658 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001659 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001660 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001661 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1662 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001663
1664 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001665 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001666 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001669 if (newTouchedWindowHandle != nullptr &&
1670 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001671 // New window supports splitting, but we should never split mouse events.
1672 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 } else if (isSplit) {
1674 // New window does not support splitting but we have already split events.
1675 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001676 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 }
1678
1679 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001680 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001682 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001683 }
1684
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001685 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1686 ALOGI("Not sending touch event to %s because it is paused",
1687 newTouchedWindowHandle->getName().c_str());
1688 newTouchedWindowHandle = nullptr;
1689 }
1690
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001691 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001692 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001693 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1694 if (!isResponsive) {
1695 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001696 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1697 newTouchedWindowHandle = nullptr;
1698 }
1699 }
1700
1701 // Also don't send the new touch event to unresponsive gesture monitors
1702 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1703
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1705 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001706 "(%d, %d) in display %" PRId32 ".",
1707 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001708 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1709 goto Failed;
1710 }
1711
1712 if (newTouchedWindowHandle != nullptr) {
1713 // Set target flags.
1714 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1715 if (isSplit) {
1716 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1719 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1720 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1721 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1722 }
1723
1724 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001725 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1726 newHoverWindowHandle = nullptr;
1727 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001728 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 }
1730
1731 // Update the temporary touch state.
1732 BitSet32 pointerIds;
1733 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 pointerIds.markBit(pointerId);
1736 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001737 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001740 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 } else {
1742 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1743
1744 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001745 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001746 if (DEBUG_FOCUS) {
1747 ALOGD("Dropping event because the pointer is not down or we previously "
1748 "dropped the pointer down event in display %" PRId32,
1749 displayId);
1750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1752 goto Failed;
1753 }
1754
1755 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001757 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001758 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1759 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
1761 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001762 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001763 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001764 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1765 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001766 if (DEBUG_FOCUS) {
1767 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1768 oldTouchedWindowHandle->getName().c_str(),
1769 newTouchedWindowHandle->getName().c_str(), displayId);
1770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001772 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1773 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1774 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775
1776 // Make a slippery entrance into the new window.
1777 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1778 isSplit = true;
1779 }
1780
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 int32_t targetFlags =
1782 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 if (isSplit) {
1784 targetFlags |= InputTarget::FLAG_SPLIT;
1785 }
1786 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1787 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1788 }
1789
1790 BitSet32 pointerIds;
1791 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001792 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001794 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
1796 }
1797 }
1798
1799 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001800 // Let the previous window know that the hover sequence is over, unless we already did it
1801 // when dispatching it as is to newTouchedWindowHandle.
1802 if (mLastHoverWindowHandle != nullptr &&
1803 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1804 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805#if DEBUG_HOVER
1806 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001807 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001809 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1810 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
1812
Garfield Tandf26e862020-07-01 20:18:19 -07001813 // Let the new window know that the hover sequence is starting, unless we already did it
1814 // when dispatching it as is to newTouchedWindowHandle.
1815 if (newHoverWindowHandle != nullptr &&
1816 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1817 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818#if DEBUG_HOVER
1819 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1823 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1824 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826 }
1827
1828 // Check permission to inject into all touched foreground windows and ensure there
1829 // is at least one touched foreground window.
1830 {
1831 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1834 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1837 injectionPermission = INJECTION_PERMISSION_DENIED;
1838 goto Failed;
1839 }
1840 }
1841 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001843 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001844 ALOGI("Dropping event because there is no touched foreground window in display "
1845 "%" PRId32 " or gesture monitor to receive it.",
1846 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1848 goto Failed;
1849 }
1850
1851 // Permission granted to injection into all touched foreground windows.
1852 injectionPermission = INJECTION_PERMISSION_GRANTED;
1853 }
1854
1855 // Check whether windows listening for outside touches are owned by the same UID. If it is
1856 // set the policy flag that we will not reveal coordinate information to this window.
1857 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1858 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001859 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001860 if (foregroundWindowHandle) {
1861 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001862 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001863 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1864 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1865 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001866 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1867 InputTarget::FLAG_ZERO_COORDS,
1868 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871 }
1872 }
1873 }
1874
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 // If this is the first pointer going down and the touched window has a wallpaper
1876 // then also add the touched wallpaper windows so they are locked in for the duration
1877 // of the touch gesture.
1878 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1879 // engine only supports touch events. We would need to add a mechanism similar
1880 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1881 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1882 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001883 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001884 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001885 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001886 getWindowHandlesLocked(displayId);
1887 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001889 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001890 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001891 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 .addOrUpdateWindow(windowHandle,
1893 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1894 InputTarget::
1895 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1896 InputTarget::FLAG_DISPATCH_AS_IS,
1897 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899 }
1900 }
1901 }
1902
1903 // Success! Output targets.
1904 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1905
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001906 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001911 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001912 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001914 }
1915
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 // Drop the outside or hover touch windows since we will not care about them
1917 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
1920Failed:
1921 // Check injection permission once and for all.
1922 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 injectionPermission = INJECTION_PERMISSION_GRANTED;
1925 } else {
1926 injectionPermission = INJECTION_PERMISSION_DENIED;
1927 }
1928 }
1929
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001930 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1931 return injectionResult;
1932 }
1933
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001935 if (!wrongDevice) {
1936 if (switchedDevice) {
1937 if (DEBUG_FOCUS) {
1938 ALOGD("Conflicting pointer actions: Switched to a different device.");
1939 }
1940 *outConflictingPointerActions = true;
1941 }
1942
1943 if (isHoverAction) {
1944 // Started hovering, therefore no longer down.
1945 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001946 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1948 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 *outConflictingPointerActions = true;
1951 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001952 tempTouchState.reset();
1953 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1954 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1955 tempTouchState.deviceId = entry.deviceId;
1956 tempTouchState.source = entry.source;
1957 tempTouchState.displayId = displayId;
1958 }
1959 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1960 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1961 // All pointers up or canceled.
1962 tempTouchState.reset();
1963 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1964 // First pointer went down.
1965 if (oldState && oldState->down) {
1966 if (DEBUG_FOCUS) {
1967 ALOGD("Conflicting pointer actions: Down received while already down.");
1968 }
1969 *outConflictingPointerActions = true;
1970 }
1971 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1972 // One pointer went up.
1973 if (isSplit) {
1974 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1975 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001977 for (size_t i = 0; i < tempTouchState.windows.size();) {
1978 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1979 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1980 touchedWindow.pointerIds.clearBit(pointerId);
1981 if (touchedWindow.pointerIds.isEmpty()) {
1982 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1983 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001988 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001989 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001990
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 // Save changes unless the action was scroll in which case the temporary touch
1992 // state was only valid for this one action.
1993 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1994 if (tempTouchState.displayId >= 0) {
1995 mTouchStatesByDisplay[displayId] = tempTouchState;
1996 } else {
1997 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002001 // Update hover state.
2002 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
2004
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 return injectionResult;
2006}
2007
2008void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009 int32_t targetFlags, BitSet32 pointerIds,
2010 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002011 std::vector<InputTarget>::iterator it =
2012 std::find_if(inputTargets.begin(), inputTargets.end(),
2013 [&windowHandle](const InputTarget& inputTarget) {
2014 return inputTarget.inputChannel->getConnectionToken() ==
2015 windowHandle->getToken();
2016 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002017
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002018 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002019
2020 if (it == inputTargets.end()) {
2021 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002022 std::shared_ptr<InputChannel> inputChannel =
2023 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002024 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
chaviw1ff3d1e2020-07-01 15:53:47 -07002038 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039}
2040
Michael Wright3dd60e22019-03-27 22:06:44 +00002041void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002042 int32_t displayId, float xOffset,
2043 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2045 mGlobalMonitorsByDisplay.find(displayId);
2046
2047 if (it != mGlobalMonitorsByDisplay.end()) {
2048 const std::vector<Monitor>& monitors = it->second;
2049 for (const Monitor& monitor : monitors) {
2050 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 }
2053}
2054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002055void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2056 float yOffset,
2057 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002058 InputTarget target;
2059 target.inputChannel = monitor.inputChannel;
2060 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002061 ui::Transform t;
2062 t.set(xOffset, yOffset);
2063 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 inputTargets.push_back(target);
2065}
2066
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 const InjectionState* injectionState) {
2069 if (injectionState &&
2070 (windowHandle == nullptr ||
2071 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2072 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002073 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 "owned by uid %d",
2076 injectionState->injectorPid, injectionState->injectorUid,
2077 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 } else {
2079 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082 return false;
2083 }
2084 return true;
2085}
2086
Robert Carrc9bf1d32020-04-13 17:21:08 -07002087/**
2088 * Indicate whether one window handle should be considered as obscuring
2089 * another window handle. We only check a few preconditions. Actually
2090 * checking the bounds is left to the caller.
2091 */
2092static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2093 const sp<InputWindowHandle>& otherHandle) {
2094 // Compare by token so cloned layers aren't counted
2095 if (haveSameToken(windowHandle, otherHandle)) {
2096 return false;
2097 }
2098 auto info = windowHandle->getInfo();
2099 auto otherInfo = otherHandle->getInfo();
2100 if (!otherInfo->visible) {
2101 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002102 } else if (info->ownerPid == otherInfo->ownerPid) {
2103 // If ownerPid is the same we don't generate occlusion events as there
2104 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002105 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002106 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002107 return false;
2108 } else if (otherInfo->displayId != info->displayId) {
2109 return false;
2110 }
2111 return true;
2112}
2113
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2115 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002117 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002118 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002119 if (windowHandle == otherHandle) {
2120 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002123 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002124 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 return true;
2126 }
2127 }
2128 return false;
2129}
2130
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002131bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2132 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002133 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002134 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002135 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002136 if (windowHandle == otherHandle) {
2137 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002138 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002139 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002140 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002141 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002142 return true;
2143 }
2144 }
2145 return false;
2146}
2147
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002148std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002149 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002151 if (applicationHandle != nullptr) {
2152 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002153 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 } else {
2155 return applicationHandle->getName();
2156 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002157 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002158 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002160 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162}
2163
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002165 if (eventEntry.type == EventEntry::Type::FOCUS) {
2166 // Focus events are passed to apps, but do not represent user activity.
2167 return;
2168 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002169 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002170 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002171 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
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002437/**
2438 * This function is purely for debugging. It helps us understand where the user interaction
2439 * was taking place. For example, if user is touching launcher, we will see a log that user
2440 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2441 * We will see both launcher and wallpaper in that list.
2442 * Once the interaction with a particular set of connections starts, no new logs will be printed
2443 * until the set of interacted connections changes.
2444 *
2445 * The following items are skipped, to reduce the logspam:
2446 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2447 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2448 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2449 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2450 * Both of those ACTION_UP events would not be logged
2451 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2452 * will not be logged. This is omitted to reduce the amount of data printed.
2453 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2454 * gesture monitor is the only connection receiving the remainder of the gesture.
2455 */
2456void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2457 const std::vector<InputTarget>& targets) {
2458 // Skip ACTION_UP events, and all events other than keys and motions
2459 if (entry.type == EventEntry::Type::KEY) {
2460 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2461 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2462 return;
2463 }
2464 } else if (entry.type == EventEntry::Type::MOTION) {
2465 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2466 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2467 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2468 return;
2469 }
2470 } else {
2471 return; // Not a key or a motion
2472 }
2473
2474 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2475 std::vector<sp<Connection>> newConnections;
2476 for (const InputTarget& target : targets) {
2477 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2478 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2479 continue; // Skip windows that receive ACTION_OUTSIDE
2480 }
2481
2482 sp<IBinder> token = target.inputChannel->getConnectionToken();
2483 sp<Connection> connection = getConnectionLocked(token);
2484 if (connection == nullptr || connection->monitor) {
2485 continue; // We only need to keep track of the non-monitor connections.
2486 }
2487 newConnectionTokens.insert(std::move(token));
2488 newConnections.emplace_back(connection);
2489 }
2490 if (newConnectionTokens == mInteractionConnectionTokens) {
2491 return; // no change
2492 }
2493 mInteractionConnectionTokens = newConnectionTokens;
2494
2495 std::string windowList;
2496 for (const sp<Connection>& connection : newConnections) {
2497 windowList += connection->getWindowName() + ", ";
2498 }
2499 std::string message = "Interaction with windows: " + windowList;
2500 if (windowList.empty()) {
2501 message += "<none>";
2502 }
2503 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2504}
2505
chaviwfd6d3512019-03-25 13:23:49 -07002506void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002507 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002508 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002509 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2510 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002511 return;
2512 }
2513
Vishnu Nairad321cd2020-08-20 16:40:21 -07002514 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2515 if (focusedToken == token) {
2516 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002517 return;
2518 }
2519
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002520 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2521 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002522 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002523 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524}
2525
2526void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002528 if (ATRACE_ENABLED()) {
2529 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002531 ATRACE_NAME(message.c_str());
2532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535#endif
2536
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002537 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2538 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002540 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002541 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002542 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543
2544 // Publish the event.
2545 status_t status;
2546 EventEntry* eventEntry = dispatchEntry->eventEntry;
2547 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002548 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002549 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2550 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002552 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002553 status =
2554 connection->inputPublisher
2555 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2556 keyEntry->deviceId, keyEntry->source,
2557 keyEntry->displayId, std::move(hmac),
2558 dispatchEntry->resolvedAction,
2559 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2560 keyEntry->scanCode, keyEntry->metaState,
2561 keyEntry->repeatCount, keyEntry->downTime,
2562 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002566 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 PointerCoords scaledCoords[MAX_POINTERS];
2570 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2571
chaviw82357092020-01-28 13:13:06 -08002572 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2574 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2575 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002576 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2578 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002579 // Don't apply window scale here since we don't want scale to affect raw
2580 // coordinates. The scale will be sent back to the client and applied
2581 // later when requesting relative coordinates.
2582 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2583 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 }
2585 usingCoords = scaledCoords;
2586 }
2587 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 // We don't want the dispatch target to know.
2589 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2590 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2591 scaledCoords[i].clear();
2592 }
2593 usingCoords = scaledCoords;
2594 }
2595 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002596
2597 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598
2599 // Publish the motion event.
2600 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002601 .publishMotionEvent(dispatchEntry->seq,
2602 dispatchEntry->resolvedEventId,
2603 motionEntry->deviceId, motionEntry->source,
2604 motionEntry->displayId, std::move(hmac),
2605 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 motionEntry->actionButton,
2607 dispatchEntry->resolvedFlags,
2608 motionEntry->edgeFlags, motionEntry->metaState,
2609 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002610 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002611 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002612 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 motionEntry->yPrecision,
2614 motionEntry->xCursorPosition,
2615 motionEntry->yCursorPosition,
2616 motionEntry->downTime, motionEntry->eventTime,
2617 motionEntry->pointerCount,
2618 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002619 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002620 break;
2621 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002622 case EventEntry::Type::FOCUS: {
2623 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2624 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002625 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002626 focusEntry->hasFocus,
2627 mInTouchMode);
2628 break;
2629 }
2630
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002631 case EventEntry::Type::CONFIGURATION_CHANGED:
2632 case EventEntry::Type::DEVICE_RESET: {
2633 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2634 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
2638
2639 // Check the result.
2640 if (status) {
2641 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002642 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 "This is unexpected because the wait queue is empty, so the pipe "
2645 "should be empty and we shouldn't have any problems writing an "
2646 "event to it, status=%d",
2647 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2649 } else {
2650 // Pipe is full and we are waiting for the app to finish process some events
2651 // before sending more events to it.
2652#if DEBUG_DISPATCH_CYCLE
2653 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002654 "waiting for the application to catch up",
2655 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 }
2658 } else {
2659 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 "status=%d",
2661 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2663 }
2664 return;
2665 }
2666
2667 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002668 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2669 connection->outboundQueue.end(),
2670 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002671 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002672 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002673 if (connection->responsive) {
2674 mAnrTracker.insert(dispatchEntry->timeoutTime,
2675 connection->inputChannel->getConnectionToken());
2676 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002677 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 }
2679}
2680
chaviw09c8d2d2020-08-24 15:48:26 -07002681std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2682 size_t size;
2683 switch (event.type) {
2684 case VerifiedInputEvent::Type::KEY: {
2685 size = sizeof(VerifiedKeyEvent);
2686 break;
2687 }
2688 case VerifiedInputEvent::Type::MOTION: {
2689 size = sizeof(VerifiedMotionEvent);
2690 break;
2691 }
2692 }
2693 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2694 return mHmacKeyManager.sign(start, size);
2695}
2696
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002697const std::array<uint8_t, 32> InputDispatcher::getSignature(
2698 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2699 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2700 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2701 // Only sign events up and down events as the purely move events
2702 // are tied to their up/down counterparts so signing would be redundant.
2703 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2704 verifiedEvent.actionMasked = actionMasked;
2705 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002706 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002707 }
2708 return INVALID_HMAC;
2709}
2710
2711const std::array<uint8_t, 32> InputDispatcher::getSignature(
2712 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2713 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2714 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2715 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002716 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002717}
2718
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 const sp<Connection>& connection, uint32_t seq,
2721 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722#if DEBUG_DISPATCH_CYCLE
2723 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#endif
2726
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 if (connection->status == Connection::STATUS_BROKEN ||
2728 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 return;
2730 }
2731
2732 // Notify other system components and prepare to start the next dispatch cycle.
2733 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2734}
2735
2736void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 const sp<Connection>& connection,
2738 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739#if DEBUG_DISPATCH_CYCLE
2740 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742#endif
2743
2744 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002745 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002746 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002747 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002748 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749
2750 // The connection appears to be unrecoverably broken.
2751 // Ignore already broken or zombie connections.
2752 if (connection->status == Connection::STATUS_NORMAL) {
2753 connection->status = Connection::STATUS_BROKEN;
2754
2755 if (notify) {
2756 // Notify other system components.
2757 onDispatchCycleBrokenLocked(currentTime, connection);
2758 }
2759 }
2760}
2761
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002762void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2763 while (!queue.empty()) {
2764 DispatchEntry* dispatchEntry = queue.front();
2765 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002766 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 }
2768}
2769
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002770void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002772 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 }
2774 delete dispatchEntry;
2775}
2776
2777int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2778 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2779
2780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002781 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002783 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 "fd=%d, events=0x%x",
2786 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 return 0; // remove the callback
2788 }
2789
2790 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002791 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2793 if (!(events & ALOOPER_EVENT_INPUT)) {
2794 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002795 "events=0x%x",
2796 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 return 1;
2798 }
2799
2800 nsecs_t currentTime = now();
2801 bool gotOne = false;
2802 status_t status;
2803 for (;;) {
2804 uint32_t seq;
2805 bool handled;
2806 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2807 if (status) {
2808 break;
2809 }
2810 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2811 gotOne = true;
2812 }
2813 if (gotOne) {
2814 d->runCommandsLockedInterruptible();
2815 if (status == WOULD_BLOCK) {
2816 return 1;
2817 }
2818 }
2819
2820 notify = status != DEAD_OBJECT || !connection->monitor;
2821 if (notify) {
2822 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825 } else {
2826 // Monitor channels are never explicitly unregistered.
2827 // We do it automatically when the remote endpoint is closed so don't warn
2828 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002829 const bool stillHaveWindowHandle =
2830 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2831 nullptr;
2832 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 if (notify) {
2834 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 "events=0x%x",
2836 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 }
2838 }
2839
2840 // Unregister the channel.
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05002841 d->unregisterInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844}
2845
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002848 for (const auto& pair : mConnectionsByFd) {
2849 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
2851}
2852
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002854 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002855 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2856 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2857}
2858
2859void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2860 const CancelationOptions& options,
2861 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2862 for (const auto& it : monitorsByDisplay) {
2863 const std::vector<Monitor>& monitors = it.second;
2864 for (const Monitor& monitor : monitors) {
2865 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002866 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002867 }
2868}
2869
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002871 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002872 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002873 if (connection == nullptr) {
2874 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002876
2877 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878}
2879
2880void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2881 const sp<Connection>& connection, const CancelationOptions& options) {
2882 if (connection->status == Connection::STATUS_BROKEN) {
2883 return;
2884 }
2885
2886 nsecs_t currentTime = now();
2887
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002888 std::vector<EventEntry*> cancelationEvents =
2889 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002891 if (cancelationEvents.empty()) {
2892 return;
2893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002895 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2896 "with reality: %s, mode=%d.",
2897 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2898 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002900
2901 InputTarget target;
2902 sp<InputWindowHandle> windowHandle =
2903 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2904 if (windowHandle != nullptr) {
2905 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002906 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002907 target.globalScaleFactor = windowInfo->globalScaleFactor;
2908 }
2909 target.inputChannel = connection->inputChannel;
2910 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2911
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002912 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2913 EventEntry* cancelationEventEntry = cancelationEvents[i];
2914 switch (cancelationEventEntry->type) {
2915 case EventEntry::Type::KEY: {
2916 logOutboundKeyDetails("cancel - ",
2917 static_cast<const KeyEntry&>(*cancelationEventEntry));
2918 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002920 case EventEntry::Type::MOTION: {
2921 logOutboundMotionDetails("cancel - ",
2922 static_cast<const MotionEntry&>(*cancelationEventEntry));
2923 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002925 case EventEntry::Type::FOCUS: {
2926 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2927 break;
2928 }
2929 case EventEntry::Type::CONFIGURATION_CHANGED:
2930 case EventEntry::Type::DEVICE_RESET: {
2931 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2932 EventEntry::typeToString(cancelationEventEntry->type));
2933 break;
2934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
2936
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002937 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2938 target, InputTarget::FLAG_DISPATCH_AS_IS);
2939
2940 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002942
2943 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944}
2945
Svet Ganov5d3bc372020-01-26 23:11:07 -08002946void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2947 const sp<Connection>& connection) {
2948 if (connection->status == Connection::STATUS_BROKEN) {
2949 return;
2950 }
2951
2952 nsecs_t currentTime = now();
2953
2954 std::vector<EventEntry*> downEvents =
2955 connection->inputState.synthesizePointerDownEvents(currentTime);
2956
2957 if (downEvents.empty()) {
2958 return;
2959 }
2960
2961#if DEBUG_OUTBOUND_EVENT_DETAILS
2962 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2963 connection->getInputChannelName().c_str(), downEvents.size());
2964#endif
2965
2966 InputTarget target;
2967 sp<InputWindowHandle> windowHandle =
2968 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2969 if (windowHandle != nullptr) {
2970 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002971 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002972 target.globalScaleFactor = windowInfo->globalScaleFactor;
2973 }
2974 target.inputChannel = connection->inputChannel;
2975 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2976
2977 for (EventEntry* downEventEntry : downEvents) {
2978 switch (downEventEntry->type) {
2979 case EventEntry::Type::MOTION: {
2980 logOutboundMotionDetails("down - ",
2981 static_cast<const MotionEntry&>(*downEventEntry));
2982 break;
2983 }
2984
2985 case EventEntry::Type::KEY:
2986 case EventEntry::Type::FOCUS:
2987 case EventEntry::Type::CONFIGURATION_CHANGED:
2988 case EventEntry::Type::DEVICE_RESET: {
2989 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2990 EventEntry::typeToString(downEventEntry->type));
2991 break;
2992 }
2993 }
2994
2995 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2996 target, InputTarget::FLAG_DISPATCH_AS_IS);
2997
2998 downEventEntry->release();
2999 }
3000
3001 startDispatchCycleLocked(currentTime, connection);
3002}
3003
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003004MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003005 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 ALOG_ASSERT(pointerIds.value != 0);
3007
3008 uint32_t splitPointerIndexMap[MAX_POINTERS];
3009 PointerProperties splitPointerProperties[MAX_POINTERS];
3010 PointerCoords splitPointerCoords[MAX_POINTERS];
3011
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 uint32_t splitPointerCount = 0;
3014
3015 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003018 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 uint32_t pointerId = uint32_t(pointerProperties.id);
3020 if (pointerIds.hasBit(pointerId)) {
3021 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3022 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3023 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003024 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 splitPointerCount += 1;
3026 }
3027 }
3028
3029 if (splitPointerCount != pointerIds.count()) {
3030 // This is bad. We are missing some of the pointers that we expected to deliver.
3031 // Most likely this indicates that we received an ACTION_MOVE events that has
3032 // different pointer ids than we expected based on the previous ACTION_DOWN
3033 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3034 // in this way.
3035 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003036 "we expected there to be %d pointers. This probably means we received "
3037 "a broken sequence of pointer ids from the input device.",
3038 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003039 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 }
3041
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3045 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3047 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003048 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 uint32_t pointerId = uint32_t(pointerProperties.id);
3050 if (pointerIds.hasBit(pointerId)) {
3051 if (pointerIds.count() == 1) {
3052 // The first/last pointer went down/up.
3053 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 ? AMOTION_EVENT_ACTION_DOWN
3055 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 } else {
3057 // A secondary pointer went down/up.
3058 uint32_t splitPointerIndex = 0;
3059 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3060 splitPointerIndex += 1;
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 action = maskedAction |
3063 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
3065 } else {
3066 // An unrelated pointer changed.
3067 action = AMOTION_EVENT_ACTION_MOVE;
3068 }
3069 }
3070
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003071 int32_t newId = mIdGenerator.nextId();
3072 if (ATRACE_ENABLED()) {
3073 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3074 ") to MotionEvent(id=0x%" PRIx32 ").",
3075 originalMotionEntry.id, newId);
3076 ATRACE_NAME(message.c_str());
3077 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003078 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003079 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3080 originalMotionEntry.source, originalMotionEntry.displayId,
3081 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003082 originalMotionEntry.actionButton, originalMotionEntry.flags,
3083 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3084 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3085 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3086 originalMotionEntry.xCursorPosition,
3087 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003088 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003090 if (originalMotionEntry.injectionState) {
3091 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 splitMotionEntry->injectionState->refCount += 1;
3093 }
3094
3095 return splitMotionEntry;
3096}
3097
3098void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3099#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003100 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101#endif
3102
3103 bool needWake;
3104 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003105 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106
Prabir Pradhan42611e02018-11-27 14:04:02 -08003107 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003108 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 needWake = enqueueInboundEventLocked(newEntry);
3110 } // release lock
3111
3112 if (needWake) {
3113 mLooper->wake();
3114 }
3115}
3116
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003117/**
3118 * If one of the meta shortcuts is detected, process them here:
3119 * Meta + Backspace -> generate BACK
3120 * Meta + Enter -> generate HOME
3121 * This will potentially overwrite keyCode and metaState.
3122 */
3123void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003125 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3126 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3127 if (keyCode == AKEYCODE_DEL) {
3128 newKeyCode = AKEYCODE_BACK;
3129 } else if (keyCode == AKEYCODE_ENTER) {
3130 newKeyCode = AKEYCODE_HOME;
3131 }
3132 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003133 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003134 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003135 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003136 keyCode = newKeyCode;
3137 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3138 }
3139 } else if (action == AKEY_EVENT_ACTION_UP) {
3140 // In order to maintain a consistent stream of up and down events, check to see if the key
3141 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3142 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003143 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003144 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003145 auto replacementIt = mReplacedKeys.find(replacement);
3146 if (replacementIt != mReplacedKeys.end()) {
3147 keyCode = replacementIt->second;
3148 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003149 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3150 }
3151 }
3152}
3153
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3155#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3157 "policyFlags=0x%x, action=0x%x, "
3158 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3159 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3160 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3161 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162#endif
3163 if (!validateKeyEvent(args->action)) {
3164 return;
3165 }
3166
3167 uint32_t policyFlags = args->policyFlags;
3168 int32_t flags = args->flags;
3169 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003170 // InputDispatcher tracks and generates key repeats on behalf of
3171 // whatever notifies it, so repeatCount should always be set to 0
3172 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3174 policyFlags |= POLICY_FLAG_VIRTUAL;
3175 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 if (policyFlags & POLICY_FLAG_FUNCTION) {
3178 metaState |= AMETA_FUNCTION_ON;
3179 }
3180
3181 policyFlags |= POLICY_FLAG_TRUSTED;
3182
Michael Wright78f24442014-08-06 15:55:28 -07003183 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003184 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003185
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003187 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003188 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3189 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
Michael Wright2b3c3302018-03-02 17:19:13 +00003191 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003193 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3194 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 bool needWake;
3199 { // acquire lock
3200 mLock.lock();
3201
3202 if (shouldSendKeyToInputFilterLocked(args)) {
3203 mLock.unlock();
3204
3205 policyFlags |= POLICY_FLAG_FILTERED;
3206 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3207 return; // event was consumed by the filter
3208 }
3209
3210 mLock.lock();
3211 }
3212
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003214 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 args->displayId, policyFlags, args->action, flags, keyCode,
3216 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
3218 needWake = enqueueInboundEventLocked(newEntry);
3219 mLock.unlock();
3220 } // release lock
3221
3222 if (needWake) {
3223 mLooper->wake();
3224 }
3225}
3226
3227bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3228 return mInputFilterEnabled;
3229}
3230
3231void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3232#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003233 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3234 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003235 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3236 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003237 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003238 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3239 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3240 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3241 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 for (uint32_t i = 0; i < args->pointerCount; i++) {
3243 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 "x=%f, y=%f, pressure=%f, size=%f, "
3245 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3246 "orientation=%f",
3247 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3251 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3252 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3253 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3254 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3255 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3256 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
3258#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3260 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 return;
3262 }
3263
3264 uint32_t policyFlags = args->policyFlags;
3265 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003266
3267 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003268 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003269 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3270 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
3274 bool needWake;
3275 { // acquire lock
3276 mLock.lock();
3277
3278 if (shouldSendMotionToInputFilterLocked(args)) {
3279 mLock.unlock();
3280
3281 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003282 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003283 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3284 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003285 args->metaState, args->buttonState, args->classification, transform,
3286 args->xPrecision, args->yPrecision, args->xCursorPosition,
3287 args->yCursorPosition, args->downTime, args->eventTime,
3288 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
3290 policyFlags |= POLICY_FLAG_FILTERED;
3291 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3292 return; // event was consumed by the filter
3293 }
3294
3295 mLock.lock();
3296 }
3297
3298 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003299 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003300 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003301 args->displayId, policyFlags, args->action, args->actionButton,
3302 args->flags, args->metaState, args->buttonState,
3303 args->classification, args->edgeFlags, args->xPrecision,
3304 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3305 args->downTime, args->pointerCount, args->pointerProperties,
3306 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
3308 needWake = enqueueInboundEventLocked(newEntry);
3309 mLock.unlock();
3310 } // release lock
3311
3312 if (needWake) {
3313 mLooper->wake();
3314 }
3315}
3316
3317bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003318 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319}
3320
3321void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3322#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003323 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 "switchMask=0x%08x",
3325 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326#endif
3327
3328 uint32_t policyFlags = args->policyFlags;
3329 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331}
3332
3333void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3334#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3336 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337#endif
3338
3339 bool needWake;
3340 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003341 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342
Prabir Pradhan42611e02018-11-27 14:04:02 -08003343 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003344 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 needWake = enqueueInboundEventLocked(newEntry);
3346 } // release lock
3347
3348 if (needWake) {
3349 mLooper->wake();
3350 }
3351}
3352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3354 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003355 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356#if DEBUG_INBOUND_EVENT_DETAILS
3357 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003358 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3359 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003361 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
3363 policyFlags |= POLICY_FLAG_INJECTED;
3364 if (hasInjectionPermission(injectorPid, injectorUid)) {
3365 policyFlags |= POLICY_FLAG_TRUSTED;
3366 }
3367
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003368 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003371 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3372 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 if (!validateKeyEvent(action)) {
3374 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003377 int32_t flags = incomingKey.getFlags();
3378 int32_t keyCode = incomingKey.getKeyCode();
3379 int32_t metaState = incomingKey.getMetaState();
3380 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003382 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003383 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003384 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3385 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3386 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003388 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3389 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003390 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391
3392 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3393 android::base::Timer t;
3394 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3395 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3396 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3397 std::to_string(t.duration().count()).c_str());
3398 }
3399 }
3400
3401 mLock.lock();
3402 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003403 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3404 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003405 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3406 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003407 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 injectedEntries.push(injectedEntry);
3409 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 case AINPUT_EVENT_TYPE_MOTION: {
3413 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3414 int32_t action = motionEvent->getAction();
3415 size_t pointerCount = motionEvent->getPointerCount();
3416 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3417 int32_t actionButton = motionEvent->getActionButton();
3418 int32_t displayId = motionEvent->getDisplayId();
3419 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3420 return INPUT_EVENT_INJECTION_FAILED;
3421 }
3422
3423 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3424 nsecs_t eventTime = motionEvent->getEventTime();
3425 android::base::Timer t;
3426 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3427 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3428 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3429 std::to_string(t.duration().count()).c_str());
3430 }
3431 }
3432
3433 mLock.lock();
3434 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3435 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3436 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003437 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3438 motionEvent->getSource(), motionEvent->getDisplayId(),
3439 policyFlags, action, actionButton, motionEvent->getFlags(),
3440 motionEvent->getMetaState(), motionEvent->getButtonState(),
3441 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3442 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003443 motionEvent->getRawXCursorPosition(),
3444 motionEvent->getRawYCursorPosition(),
3445 motionEvent->getDownTime(), uint32_t(pointerCount),
3446 pointerProperties, samplePointerCoords,
3447 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 injectedEntries.push(injectedEntry);
3449 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3450 sampleEventTimes += 1;
3451 samplePointerCoords += pointerCount;
3452 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003453 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003454 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003455 motionEvent->getDisplayId(), policyFlags, action,
3456 actionButton, motionEvent->getFlags(),
3457 motionEvent->getMetaState(), motionEvent->getButtonState(),
3458 motionEvent->getClassification(),
3459 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3460 motionEvent->getYPrecision(),
3461 motionEvent->getRawXCursorPosition(),
3462 motionEvent->getRawYCursorPosition(),
3463 motionEvent->getDownTime(), uint32_t(pointerCount),
3464 pointerProperties, samplePointerCoords,
3465 motionEvent->getXOffset(), motionEvent->getYOffset());
3466 injectedEntries.push(nextInjectedEntry);
3467 }
3468 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003472 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475
3476 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3477 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3478 injectionState->injectionIsAsync = true;
3479 }
3480
3481 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003482 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
3484 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003485 while (!injectedEntries.empty()) {
3486 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3487 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 }
3489
3490 mLock.unlock();
3491
3492 if (needWake) {
3493 mLooper->wake();
3494 }
3495
3496 int32_t injectionResult;
3497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003498 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3501 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3502 } else {
3503 for (;;) {
3504 injectionResult = injectionState->injectionResult;
3505 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3506 break;
3507 }
3508
3509 nsecs_t remainingTimeout = endTime - now();
3510 if (remainingTimeout <= 0) {
3511#if DEBUG_INJECTION
3512 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003513 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514#endif
3515 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3516 break;
3517 }
3518
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003519 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 }
3521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3523 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 while (injectionState->pendingForegroundDispatches != 0) {
3525#if DEBUG_INJECTION
3526 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528#endif
3529 nsecs_t remainingTimeout = endTime - now();
3530 if (remainingTimeout <= 0) {
3531#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003532 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3533 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534#endif
3535 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3536 break;
3537 }
3538
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003539 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
3541 }
3542 }
3543
3544 injectionState->release();
3545 } // release lock
3546
3547#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003548 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003549 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550#endif
3551
3552 return injectionResult;
3553}
3554
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003555std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003556 std::array<uint8_t, 32> calculatedHmac;
3557 std::unique_ptr<VerifiedInputEvent> result;
3558 switch (event.getType()) {
3559 case AINPUT_EVENT_TYPE_KEY: {
3560 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3561 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3562 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003563 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003564 break;
3565 }
3566 case AINPUT_EVENT_TYPE_MOTION: {
3567 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3568 VerifiedMotionEvent verifiedMotionEvent =
3569 verifiedMotionEventFromMotionEvent(motionEvent);
3570 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003571 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003572 break;
3573 }
3574 default: {
3575 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3576 return nullptr;
3577 }
3578 }
3579 if (calculatedHmac == INVALID_HMAC) {
3580 return nullptr;
3581 }
3582 if (calculatedHmac != event.getHmac()) {
3583 return nullptr;
3584 }
3585 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003586}
3587
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 return injectorUid == 0 ||
3590 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591}
3592
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003593void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 InjectionState* injectionState = entry->injectionState;
3595 if (injectionState) {
3596#if DEBUG_INJECTION
3597 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 "injectorPid=%d, injectorUid=%d",
3599 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600#endif
3601
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003602 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 // Log the outcome since the injector did not wait for the injection result.
3604 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 case INPUT_EVENT_INJECTION_SUCCEEDED:
3606 ALOGV("Asynchronous input event injection succeeded.");
3607 break;
3608 case INPUT_EVENT_INJECTION_FAILED:
3609 ALOGW("Asynchronous input event injection failed.");
3610 break;
3611 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3612 ALOGW("Asynchronous input event injection permission denied.");
3613 break;
3614 case INPUT_EVENT_INJECTION_TIMED_OUT:
3615 ALOGW("Asynchronous input event injection timed out.");
3616 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618 }
3619
3620 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003621 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623}
3624
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003625void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 InjectionState* injectionState = entry->injectionState;
3627 if (injectionState) {
3628 injectionState->pendingForegroundDispatches += 1;
3629 }
3630}
3631
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003632void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 InjectionState* injectionState = entry->injectionState;
3634 if (injectionState) {
3635 injectionState->pendingForegroundDispatches -= 1;
3636
3637 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003638 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
3640 }
3641}
3642
Vishnu Nairad321cd2020-08-20 16:40:21 -07003643const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003644 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003645 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3646 auto it = mWindowHandlesByDisplay.find(displayId);
3647 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003648}
3649
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003651 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003652 if (windowHandleToken == nullptr) {
3653 return nullptr;
3654 }
3655
Arthur Hungb92218b2018-08-14 12:00:21 +08003656 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003657 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003658 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003659 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003660 return windowHandle;
3661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003664 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665}
3666
Vishnu Nairad321cd2020-08-20 16:40:21 -07003667sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3668 int displayId) const {
3669 if (windowHandleToken == nullptr) {
3670 return nullptr;
3671 }
3672
3673 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3674 if (windowHandle->getToken() == windowHandleToken) {
3675 return windowHandle;
3676 }
3677 }
3678 return nullptr;
3679}
3680
3681sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3682 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3683 return getWindowHandleLocked(focusedToken, displayId);
3684}
3685
Mady Mellor017bcd12020-06-23 19:12:00 +00003686bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3687 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003688 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003689 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003690 if (handle->getId() == windowHandle->getId() &&
3691 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003692 if (windowHandle->getInfo()->displayId != it.first) {
3693 ALOGE("Found window %s in display %" PRId32
3694 ", but it should belong to display %" PRId32,
3695 windowHandle->getName().c_str(), it.first,
3696 windowHandle->getInfo()->displayId);
3697 }
3698 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701 }
3702 return false;
3703}
3704
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003705bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3706 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3707 const bool noInputChannel =
3708 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3709 if (connection != nullptr && noInputChannel) {
3710 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3711 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3712 return false;
3713 }
3714
3715 if (connection == nullptr) {
3716 if (!noInputChannel) {
3717 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3718 }
3719 return false;
3720 }
3721 if (!connection->responsive) {
3722 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3723 return false;
3724 }
3725 return true;
3726}
3727
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003728std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3729 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003730 size_t count = mInputChannelsByToken.count(token);
3731 if (count == 0) {
3732 return nullptr;
3733 }
3734 return mInputChannelsByToken.at(token);
3735}
3736
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003737void InputDispatcher::updateWindowHandlesForDisplayLocked(
3738 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3739 if (inputWindowHandles.empty()) {
3740 // Remove all handles on a display if there are no windows left.
3741 mWindowHandlesByDisplay.erase(displayId);
3742 return;
3743 }
3744
3745 // Since we compare the pointer of input window handles across window updates, we need
3746 // to make sure the handle object for the same window stays unchanged across updates.
3747 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003748 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003749 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003750 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003751 }
3752
3753 std::vector<sp<InputWindowHandle>> newHandles;
3754 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3755 if (!handle->updateInfo()) {
3756 // handle no longer valid
3757 continue;
3758 }
3759
3760 const InputWindowInfo* info = handle->getInfo();
3761 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3762 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3763 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003764 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3765 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3766 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003767 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003768 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003769 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003770 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003771 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003772 }
3773
3774 if (info->displayId != displayId) {
3775 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3776 handle->getName().c_str(), displayId, info->displayId);
3777 continue;
3778 }
3779
Robert Carredd13602020-04-13 17:24:34 -07003780 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3781 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003782 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003783 oldHandle->updateFrom(handle);
3784 newHandles.push_back(oldHandle);
3785 } else {
3786 newHandles.push_back(handle);
3787 }
3788 }
3789
3790 // Insert or replace
3791 mWindowHandlesByDisplay[displayId] = newHandles;
3792}
3793
Arthur Hung72d8dc32020-03-28 00:48:39 +00003794void InputDispatcher::setInputWindows(
3795 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3796 { // acquire lock
3797 std::scoped_lock _l(mLock);
3798 for (auto const& i : handlesPerDisplay) {
3799 setInputWindowsLocked(i.second, i.first);
3800 }
3801 }
3802 // Wake up poll loop since it may need to make new input dispatching choices.
3803 mLooper->wake();
3804}
3805
Arthur Hungb92218b2018-08-14 12:00:21 +08003806/**
3807 * Called from InputManagerService, update window handle list by displayId that can receive input.
3808 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3809 * If set an empty list, remove all handles from the specific display.
3810 * For focused handle, check if need to change and send a cancel event to previous one.
3811 * For removed handle, check if need to send a cancel event if already in touch.
3812 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003813void InputDispatcher::setInputWindowsLocked(
3814 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003815 if (DEBUG_FOCUS) {
3816 std::string windowList;
3817 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3818 windowList += iwh->getName() + " ";
3819 }
3820 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003823 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3824 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3825 const bool noInputWindow =
3826 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3827 if (noInputWindow && window->getToken() != nullptr) {
3828 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3829 window->getName().c_str());
3830 window->releaseChannel();
3831 }
3832 }
3833
Arthur Hung72d8dc32020-03-28 00:48:39 +00003834 // Copy old handles for release if they are no longer present.
3835 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Arthur Hung72d8dc32020-03-28 00:48:39 +00003837 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003838
Vishnu Nair958da932020-08-21 17:12:37 -07003839 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3840 if (mLastHoverWindowHandle &&
3841 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3842 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003843 mLastHoverWindowHandle = nullptr;
3844 }
3845
Vishnu Nair958da932020-08-21 17:12:37 -07003846 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3847 if (focusedToken) {
3848 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3849 if (result != FocusResult::OK) {
3850 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3851 }
3852 }
3853
3854 std::optional<FocusRequest> focusRequest =
3855 getOptionalValueByKey(mPendingFocusRequests, displayId);
3856 if (focusRequest) {
3857 // If the window from the pending request is now visible, provide it focus.
3858 FocusResult result = handleFocusRequestLocked(*focusRequest);
3859 if (result != FocusResult::NOT_VISIBLE) {
3860 // Drop the request if we were able to change the focus or we cannot change
3861 // it for another reason.
3862 mPendingFocusRequests.erase(displayId);
3863 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003866 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3867 mTouchStatesByDisplay.find(displayId);
3868 if (stateIt != mTouchStatesByDisplay.end()) {
3869 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003870 for (size_t i = 0; i < state.windows.size();) {
3871 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003872 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003873 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003874 ALOGD("Touched window was removed: %s in display %" PRId32,
3875 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003876 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003877 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003878 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3879 if (touchedInputChannel != nullptr) {
3880 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3881 "touched window was removed");
3882 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003884 state.windows.erase(state.windows.begin() + i);
3885 } else {
3886 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 }
3888 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003889 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003890
Arthur Hung72d8dc32020-03-28 00:48:39 +00003891 // Release information for windows that are no longer present.
3892 // This ensures that unused input channels are released promptly.
3893 // Otherwise, they might stick around until the window handle is destroyed
3894 // which might not happen until the next GC.
3895 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003896 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003897 if (DEBUG_FOCUS) {
3898 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003899 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003900 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003901 }
chaviw291d88a2019-02-14 10:33:58 -08003902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903}
3904
3905void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003906 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003907 if (DEBUG_FOCUS) {
3908 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3909 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3910 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003912 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
Chris Yea209fde2020-07-22 13:54:51 -07003914 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003915 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003916
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003917 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
3918 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003919 }
3920
Chris Yea209fde2020-07-22 13:54:51 -07003921 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003922 if (inputApplicationHandle != nullptr) {
3923 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3924 } else {
3925 mFocusedApplicationHandlesByDisplay.erase(displayId);
3926 }
3927
3928 // No matter what the old focused application was, stop waiting on it because it is
3929 // no longer focused.
3930 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 } // release lock
3932
3933 // Wake up poll loop since it may need to make new input dispatching choices.
3934 mLooper->wake();
3935}
3936
Tiger Huang721e26f2018-07-24 22:26:19 +08003937/**
3938 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3939 * the display not specified.
3940 *
3941 * We track any unreleased events for each window. If a window loses the ability to receive the
3942 * released event, we will send a cancel event to it. So when the focused display is changed, we
3943 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3944 * display. The display-specified events won't be affected.
3945 */
3946void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003947 if (DEBUG_FOCUS) {
3948 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3949 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003952
3953 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003954 sp<IBinder> oldFocusedWindowToken =
3955 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3956 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003957 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003958 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003959 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 CancelationOptions
3961 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3962 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003963 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003964 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3965 }
3966 }
3967 mFocusedDisplayId = displayId;
3968
Chris Ye3c2d6f52020-08-09 10:39:48 -07003969 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003970 sp<IBinder> newFocusedWindowToken =
3971 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3972 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003973
Vishnu Nairad321cd2020-08-20 16:40:21 -07003974 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003975 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003976 if (!mFocusedWindowTokenByDisplay.empty()) {
3977 ALOGE("But another display has a focused window\n%s",
3978 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003979 }
3980 }
3981 }
3982
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003983 if (DEBUG_FOCUS) {
3984 logDispatchStateLocked();
3985 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003986 } // release lock
3987
3988 // Wake up poll loop since it may need to make new input dispatching choices.
3989 mLooper->wake();
3990}
3991
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003993 if (DEBUG_FOCUS) {
3994 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996
3997 bool changed;
3998 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003999 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
4001 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4002 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004003 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 }
4005
4006 if (mDispatchEnabled && !enabled) {
4007 resetAndDropEverythingLocked("dispatcher is being disabled");
4008 }
4009
4010 mDispatchEnabled = enabled;
4011 mDispatchFrozen = frozen;
4012 changed = true;
4013 } else {
4014 changed = false;
4015 }
4016
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004017 if (DEBUG_FOCUS) {
4018 logDispatchStateLocked();
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 } // release lock
4021
4022 if (changed) {
4023 // Wake up poll loop since it may need to make new input dispatching choices.
4024 mLooper->wake();
4025 }
4026}
4027
4028void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004029 if (DEBUG_FOCUS) {
4030 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032
4033 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004034 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
4036 if (mInputFilterEnabled == enabled) {
4037 return;
4038 }
4039
4040 mInputFilterEnabled = enabled;
4041 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4042 } // release lock
4043
4044 // Wake up poll loop since there might be work to do to drop everything.
4045 mLooper->wake();
4046}
4047
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004048void InputDispatcher::setInTouchMode(bool inTouchMode) {
4049 std::scoped_lock lock(mLock);
4050 mInTouchMode = inTouchMode;
4051}
4052
chaviwfbe5d9c2018-12-26 12:23:37 -08004053bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4054 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004055 if (DEBUG_FOCUS) {
4056 ALOGD("Trivial transfer to same window.");
4057 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004058 return true;
4059 }
4060
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004062 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
chaviwfbe5d9c2018-12-26 12:23:37 -08004064 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4065 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004066 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004067 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 return false;
4069 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004070 if (DEBUG_FOCUS) {
4071 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4072 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004075 if (DEBUG_FOCUS) {
4076 ALOGD("Cannot transfer focus because windows are on different displays.");
4077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 return false;
4079 }
4080
4081 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004082 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4083 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004084 for (size_t i = 0; i < state.windows.size(); i++) {
4085 const TouchedWindow& touchedWindow = state.windows[i];
4086 if (touchedWindow.windowHandle == fromWindowHandle) {
4087 int32_t oldTargetFlags = touchedWindow.targetFlags;
4088 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004090 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 int32_t newTargetFlags = oldTargetFlags &
4093 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4094 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004095 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
Jeff Brownf086ddb2014-02-11 14:28:48 -08004097 found = true;
4098 goto Found;
4099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 }
4101 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004105 if (DEBUG_FOCUS) {
4106 ALOGD("Focus transfer failed because from window did not have focus.");
4107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 return false;
4109 }
4110
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004111 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4112 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004113 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004114 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 CancelationOptions
4116 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4117 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004119 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
4121
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004122 if (DEBUG_FOCUS) {
4123 logDispatchStateLocked();
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 } // release lock
4126
4127 // Wake up poll loop since it may need to make new input dispatching choices.
4128 mLooper->wake();
4129 return true;
4130}
4131
4132void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004133 if (DEBUG_FOCUS) {
4134 ALOGD("Resetting and dropping all events (%s).", reason);
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136
4137 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4138 synthesizeCancelationEventsForAllConnectionsLocked(options);
4139
4140 resetKeyRepeatLocked();
4141 releasePendingEventLocked();
4142 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004143 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004145 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004146 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004148 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149}
4150
4151void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 dumpDispatchStateLocked(dump);
4154
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004155 std::istringstream stream(dump);
4156 std::string line;
4157
4158 while (std::getline(stream, line, '\n')) {
4159 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
4161}
4162
Vishnu Nairad321cd2020-08-20 16:40:21 -07004163std::string InputDispatcher::dumpFocusedWindowsLocked() {
4164 if (mFocusedWindowTokenByDisplay.empty()) {
4165 return INDENT "FocusedWindows: <none>\n";
4166 }
4167
4168 std::string dump;
4169 dump += INDENT "FocusedWindows:\n";
4170 for (auto& it : mFocusedWindowTokenByDisplay) {
4171 const int32_t displayId = it.first;
4172 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4173 if (windowHandle) {
4174 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4175 windowHandle->getName().c_str());
4176 } else {
4177 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4178 " has focused token without a window'\n",
4179 displayId);
4180 }
4181 }
4182 return dump;
4183}
4184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004186 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4187 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4188 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004189 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190
Tiger Huang721e26f2018-07-24 22:26:19 +08004191 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4192 dump += StringPrintf(INDENT "FocusedApplications:\n");
4193 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4194 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004195 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004196 const std::chrono::duration timeout =
4197 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004199 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004200 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004203 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004205
Vishnu Nairad321cd2020-08-20 16:40:21 -07004206 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004208 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004210 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4211 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 state.displayId, toString(state.down), toString(state.split),
4214 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004215 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004217 for (size_t i = 0; i < state.windows.size(); i++) {
4218 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004219 dump += StringPrintf(INDENT4
4220 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4221 i, touchedWindow.windowHandle->getName().c_str(),
4222 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004223 }
4224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004226 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004227 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004228 dump += INDENT3 "Portal windows:\n";
4229 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004230 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004231 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4232 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004233 }
4234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 }
4236 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239
Arthur Hungb92218b2018-08-14 12:00:21 +08004240 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004242 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004243 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004244 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004245 dump += INDENT2 "Windows:\n";
4246 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004247 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004248 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
Arthur Hungb92218b2018-08-14 12:00:21 +08004250 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004251 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4252 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004253 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004255 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004256 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 i, windowInfo->name.c_str(), windowInfo->displayId,
4258 windowInfo->portalToDisplayId,
4259 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004260 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 toString(windowInfo->hasWallpaper),
4262 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004263 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004264 static_cast<int32_t>(windowInfo->type),
4265 windowInfo->frameLeft, windowInfo->frameTop,
4266 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004267 windowInfo->globalScaleFactor,
4268 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004269 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004270 dump += StringPrintf(", inputFeatures=%s",
4271 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004272 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4273 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004275 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004276 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004277 }
4278 } else {
4279 dump += INDENT2 "Windows: <none>\n";
4280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004283 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 }
4285
Michael Wright3dd60e22019-03-27 22:06:44 +00004286 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004288 const std::vector<Monitor>& monitors = it.second;
4289 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4290 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 }
4292 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004293 const std::vector<Monitor>& monitors = it.second;
4294 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4295 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004298 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
4300
4301 nsecs_t currentTime = now();
4302
4303 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004304 if (!mRecentQueue.empty()) {
4305 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4306 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004307 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004309 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004312 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314
4315 // Dump event currently being dispatched.
4316 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317 dump += INDENT "PendingEvent:\n";
4318 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004320 dump += StringPrintf(", age=%" PRId64 "ms\n",
4321 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004323 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325
4326 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004327 if (!mInboundQueue.empty()) {
4328 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4329 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004330 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004332 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004335 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 }
4337
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004338 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004339 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004340 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4341 const KeyReplacement& replacement = pair.first;
4342 int32_t newKeyCode = pair.second;
4343 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004345 }
4346 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004347 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004348 }
4349
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004350 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004352 for (const auto& pair : mConnectionsByFd) {
4353 const sp<Connection>& connection = pair.second;
4354 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004355 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004356 pair.first, connection->getInputChannelName().c_str(),
4357 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004358 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004360 if (!connection->outboundQueue.empty()) {
4361 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4362 connection->outboundQueue.size());
4363 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 dump.append(INDENT4);
4365 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004366 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4367 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004369 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 }
4371 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004372 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004375 if (!connection->waitQueue.empty()) {
4376 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4377 connection->waitQueue.size());
4378 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004381 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004382 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004385 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 }
4387 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004388 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 }
4390 }
4391 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004392 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 }
4394
4395 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004396 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4397 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004399 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 }
4401
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004402 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004403 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4404 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4405 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406}
4407
Michael Wright3dd60e22019-03-27 22:06:44 +00004408void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4409 const size_t numMonitors = monitors.size();
4410 for (size_t i = 0; i < numMonitors; i++) {
4411 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004412 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004413 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4414 dump += "\n";
4415 }
4416}
4417
Garfield Tan400128f2020-09-22 21:53:55 +00004418status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
4419#if DEBUG_REGISTRATION
4420 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421#endif
4422
4423 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004424 std::scoped_lock _l(mLock);
Garfield Tan400128f2020-09-22 21:53:55 +00004425 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
4426 if (existingConnection != nullptr) {
4427 ALOGW("Attempted to register already registered input channel '%s'",
4428 inputChannel->getName().c_str());
4429 return BAD_VALUE;
4430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Garfield Tan400128f2020-09-22 21:53:55 +00004432 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
4433
4434 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004435 mConnectionsByFd[fd] = connection;
Garfield Tan400128f2020-09-22 21:53:55 +00004436 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4439 } // release lock
4440
4441 // Wake the looper because some connections have changed.
4442 mLooper->wake();
Garfield Tan400128f2020-09-22 21:53:55 +00004443 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444}
4445
Garfield Tan400128f2020-09-22 21:53:55 +00004446status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
4447 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004448 { // acquire lock
4449 std::scoped_lock _l(mLock);
4450
4451 if (displayId < 0) {
Garfield Tan400128f2020-09-22 21:53:55 +00004452 ALOGW("Attempted to register input monitor without a specified display.");
4453 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00004454 }
4455
Garfield Tan400128f2020-09-22 21:53:55 +00004456 if (inputChannel->getConnectionToken() == nullptr) {
4457 ALOGW("Attempted to register input monitor without an identifying token.");
4458 return BAD_VALUE;
4459 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004460
Garfield Tan400128f2020-09-22 21:53:55 +00004461 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
4462
4463 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004464 mConnectionsByFd[fd] = connection;
Garfield Tan400128f2020-09-22 21:53:55 +00004465 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004466
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 auto& monitorsByDisplay =
4468 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan400128f2020-09-22 21:53:55 +00004469 monitorsByDisplay[displayId].emplace_back(inputChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004470
4471 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004472 }
4473 // Wake the looper because some connections have changed.
4474 mLooper->wake();
Garfield Tan400128f2020-09-22 21:53:55 +00004475 return OK;
Michael Wright3dd60e22019-03-27 22:06:44 +00004476}
4477
Garfield Tan400128f2020-09-22 21:53:55 +00004478status_t InputDispatcher::unregisterInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004480 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004482 status_t status = unregisterInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 if (status) {
4484 return status;
4485 }
4486 } // release lock
4487
4488 // Wake the poll loop because removing the connection may have changed the current
4489 // synchronization state.
4490 mLooper->wake();
4491 return OK;
4492}
4493
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004494status_t InputDispatcher::unregisterInputChannelLocked(const sp<IBinder>& connectionToken,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004496 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004497 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004498 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 return BAD_VALUE;
4500 }
4501
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004502 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004503 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004504
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004506 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 }
4508
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004509 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
4511 nsecs_t currentTime = now();
4512 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4513
4514 connection->status = Connection::STATUS_ZOMBIE;
4515 return OK;
4516}
4517
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004518void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4519 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4520 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004521}
4522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004524 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004525 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004527 std::vector<Monitor>& monitors = it->second;
4528 const size_t numMonitors = monitors.size();
4529 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004530 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 monitors.erase(monitors.begin() + i);
4532 break;
4533 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004534 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004535 if (monitors.empty()) {
4536 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004537 } else {
4538 ++it;
4539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 }
4541}
4542
Michael Wright3dd60e22019-03-27 22:06:44 +00004543status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4544 { // acquire lock
4545 std::scoped_lock _l(mLock);
4546 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4547
4548 if (!foundDisplayId) {
4549 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4550 return BAD_VALUE;
4551 }
4552 int32_t displayId = foundDisplayId.value();
4553
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004554 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4555 mTouchStatesByDisplay.find(displayId);
4556 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004557 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4558 return BAD_VALUE;
4559 }
4560
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004561 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004562 std::optional<int32_t> foundDeviceId;
4563 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004564 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004565 foundDeviceId = state.deviceId;
4566 }
4567 }
4568 if (!foundDeviceId || !state.down) {
4569 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004571 return BAD_VALUE;
4572 }
4573 int32_t deviceId = foundDeviceId.value();
4574
4575 // Send cancel events to all the input channels we're stealing from.
4576 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004578 options.deviceId = deviceId;
4579 options.displayId = displayId;
4580 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004581 std::shared_ptr<InputChannel> channel =
4582 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004583 if (channel != nullptr) {
4584 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4585 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004586 }
4587 // Then clear the current touch state so we stop dispatching to them as well.
4588 state.filterNonMonitors();
4589 }
4590 return OK;
4591}
4592
Michael Wright3dd60e22019-03-27 22:06:44 +00004593std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4594 const sp<IBinder>& token) {
4595 for (const auto& it : mGestureMonitorsByDisplay) {
4596 const std::vector<Monitor>& monitors = it.second;
4597 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004598 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004599 return it.first;
4600 }
4601 }
4602 }
4603 return std::nullopt;
4604}
4605
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004606sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004607 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004608 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004609 }
4610
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004611 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004612 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004613 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004614 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 }
4616 }
Robert Carr4e670e52018-08-15 13:26:12 -07004617
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004618 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004621void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004623 removeByValue(mConnectionsByFd, connection);
4624}
4625
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004626void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4627 const sp<Connection>& connection, uint32_t seq,
4628 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004629 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4630 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 commandEntry->connection = connection;
4632 commandEntry->eventTime = currentTime;
4633 commandEntry->seq = seq;
4634 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004635 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636}
4637
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4639 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004643 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4644 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004646 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647}
4648
Vishnu Nairad321cd2020-08-20 16:40:21 -07004649void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4650 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004651 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4652 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004653 commandEntry->oldToken = oldToken;
4654 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004655 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004656}
4657
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004658void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4659 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4660 // is already healthy again. Don't raise ANR in this situation
4661 if (connection->waitQueue.empty()) {
4662 ALOGI("Not raising ANR because the connection %s has recovered",
4663 connection->inputChannel->getName().c_str());
4664 return;
4665 }
4666 /**
4667 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4668 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4669 * has changed. This could cause newer entries to time out before the already dispatched
4670 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4671 * processes the events linearly. So providing information about the oldest entry seems to be
4672 * most useful.
4673 */
4674 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4675 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4676 std::string reason =
4677 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4678 connection->inputChannel->getName().c_str(),
4679 ns2ms(currentWait),
4680 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4683 reason);
4684
4685 std::unique_ptr<CommandEntry> commandEntry =
4686 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4687 commandEntry->inputApplicationHandle = nullptr;
4688 commandEntry->inputChannel = connection->inputChannel;
4689 commandEntry->reason = std::move(reason);
4690 postCommandLocked(std::move(commandEntry));
4691}
4692
Chris Yea209fde2020-07-22 13:54:51 -07004693void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4695 application->getName().c_str());
4696
4697 updateLastAnrStateLocked(application, reason);
4698
4699 std::unique_ptr<CommandEntry> commandEntry =
4700 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4701 commandEntry->inputApplicationHandle = application;
4702 commandEntry->inputChannel = nullptr;
4703 commandEntry->reason = std::move(reason);
4704 postCommandLocked(std::move(commandEntry));
4705}
4706
4707void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4708 const std::string& reason) {
4709 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4710 updateLastAnrStateLocked(windowLabel, reason);
4711}
4712
Chris Yea209fde2020-07-22 13:54:51 -07004713void InputDispatcher::updateLastAnrStateLocked(
4714 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004715 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4716 updateLastAnrStateLocked(windowLabel, reason);
4717}
4718
4719void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4720 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004722 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 struct tm tm;
4724 localtime_r(&t, &tm);
4725 char timestr[64];
4726 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004727 mLastAnrState.clear();
4728 mLastAnrState += INDENT "ANR:\n";
4729 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4731 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004732 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733}
4734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 mLock.unlock();
4737
4738 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4739
4740 mLock.lock();
4741}
4742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 sp<Connection> connection = commandEntry->connection;
4745
4746 if (connection->status != Connection::STATUS_ZOMBIE) {
4747 mLock.unlock();
4748
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004749 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750
4751 mLock.lock();
4752 }
4753}
4754
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004755void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004756 sp<IBinder> oldToken = commandEntry->oldToken;
4757 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004758 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004759 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004760 mLock.lock();
4761}
4762
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004763void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004764 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004765 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 mLock.unlock();
4767
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004768 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004769 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
4771 mLock.lock();
4772
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004773 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4775 } else {
4776 // stop waking up for events in this connection, it is already not responding
4777 sp<Connection> connection = getConnectionLocked(token);
4778 if (connection == nullptr) {
4779 return;
4780 }
4781 cancelEventsForAnrLocked(connection);
4782 }
4783}
4784
Chris Yea209fde2020-07-22 13:54:51 -07004785void InputDispatcher::extendAnrTimeoutsLocked(
4786 const std::shared_ptr<InputApplicationHandle>& application,
4787 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788 sp<Connection> connection = getConnectionLocked(connectionToken);
4789 if (connection == nullptr) {
4790 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4791 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004792 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 mAwaitedFocusedApplication = application;
4794 } else {
4795 // It's also possible that the connection already disappeared. No action necessary.
4796 }
4797 return;
4798 }
4799
4800 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004801 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802
4803 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004804 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805 for (DispatchEntry* entry : connection->waitQueue) {
4806 if (newTimeout >= entry->timeoutTime) {
4807 // Already removed old entries when connection was marked unresponsive
4808 entry->timeoutTime = newTimeout;
4809 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4810 }
4811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812}
4813
4814void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4815 CommandEntry* commandEntry) {
4816 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004817 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
4819 mLock.unlock();
4820
Michael Wright2b3c3302018-03-02 17:19:13 +00004821 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004823 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004824 : nullptr;
4825 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004826 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4827 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830
4831 mLock.lock();
4832
4833 if (delay < 0) {
4834 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4835 } else if (!delay) {
4836 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4837 } else {
4838 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4839 entry->interceptKeyWakeupTime = now() + delay;
4840 }
4841 entry->release();
4842}
4843
chaviwfd6d3512019-03-25 13:23:49 -07004844void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4845 mLock.unlock();
4846 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4847 mLock.lock();
4848}
4849
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850/**
4851 * Connection is responsive if it has no events in the waitQueue that are older than the
4852 * current time.
4853 */
4854static bool isConnectionResponsive(const Connection& connection) {
4855 const nsecs_t currentTime = now();
4856 for (const DispatchEntry* entry : connection.waitQueue) {
4857 if (entry->timeoutTime < currentTime) {
4858 return false;
4859 }
4860 }
4861 return true;
4862}
4863
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004864void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004866 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869
4870 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004871 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004872 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004873 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004875 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004876 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004877 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004878 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4879 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004880 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004881 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004882
4883 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004884 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004885 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4886 restartEvent =
4887 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004888 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004889 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4890 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4891 handled);
4892 } else {
4893 restartEvent = false;
4894 }
4895
4896 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004897 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004898 // contents of the wait queue to have been drained, so we need to double-check
4899 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004900 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4901 if (dispatchEntryIt != connection->waitQueue.end()) {
4902 dispatchEntry = *dispatchEntryIt;
4903 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 mAnrTracker.erase(dispatchEntry->timeoutTime,
4905 connection->inputChannel->getConnectionToken());
4906 if (!connection->responsive) {
4907 connection->responsive = isConnectionResponsive(*connection);
4908 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004909 traceWaitQueueLength(connection);
4910 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004911 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004912 traceOutboundQueueLength(connection);
4913 } else {
4914 releaseDispatchEntry(dispatchEntry);
4915 }
4916 }
4917
4918 // Start the next dispatch cycle for this connection.
4919 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920}
4921
4922bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004923 DispatchEntry* dispatchEntry,
4924 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004925 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004926 if (!handled) {
4927 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004928 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004929 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004930 return false;
4931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004933 // Get the fallback key state.
4934 // Clear it out after dispatching the UP.
4935 int32_t originalKeyCode = keyEntry->keyCode;
4936 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4937 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4938 connection->inputState.removeFallbackKey(originalKeyCode);
4939 }
4940
4941 if (handled || !dispatchEntry->hasForegroundTarget()) {
4942 // If the application handles the original key for which we previously
4943 // generated a fallback or if the window is not a foreground window,
4944 // then cancel the associated fallback key, if any.
4945 if (fallbackKeyCode != -1) {
4946 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004948 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004949 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4950 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4951 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004953 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
4956 mLock.unlock();
4957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004958 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960
4961 mLock.lock();
4962
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004963 // Cancel the fallback key.
4964 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004966 "application handled the original non-fallback key "
4967 "or is no longer a foreground target, "
4968 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 options.keyCode = fallbackKeyCode;
4970 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004972 connection->inputState.removeFallbackKey(originalKeyCode);
4973 }
4974 } else {
4975 // If the application did not handle a non-fallback key, first check
4976 // that we are in a good state to perform unhandled key event processing
4977 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004979 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004982 "since this is not an initial down. "
4983 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4984 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004986 return false;
4987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004989 // Dispatch the unhandled key to the policy.
4990#if DEBUG_OUTBOUND_EVENT_DETAILS
4991 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004992 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4993 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004994#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004995 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004996
4997 mLock.unlock();
4998
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004999 bool fallback =
5000 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5001 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005002
5003 mLock.lock();
5004
5005 if (connection->status != Connection::STATUS_NORMAL) {
5006 connection->inputState.removeFallbackKey(originalKeyCode);
5007 return false;
5008 }
5009
5010 // Latch the fallback keycode for this key on an initial down.
5011 // The fallback keycode cannot change at any other point in the lifecycle.
5012 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005014 fallbackKeyCode = event.getKeyCode();
5015 } else {
5016 fallbackKeyCode = AKEYCODE_UNKNOWN;
5017 }
5018 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5019 }
5020
5021 ALOG_ASSERT(fallbackKeyCode != -1);
5022
5023 // Cancel the fallback key if the policy decides not to send it anymore.
5024 // We will continue to dispatch the key to the policy but we will no
5025 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005026 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5027 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005028#if DEBUG_OUTBOUND_EVENT_DETAILS
5029 if (fallback) {
5030 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005031 "as a fallback for %d, but on the DOWN it had requested "
5032 "to send %d instead. Fallback canceled.",
5033 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005034 } else {
5035 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 "but on the DOWN it had requested to send %d. "
5037 "Fallback canceled.",
5038 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005039 }
5040#endif
5041
5042 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5043 "canceling fallback, policy no longer desires it");
5044 options.keyCode = fallbackKeyCode;
5045 synthesizeCancelationEventsForConnectionLocked(connection, options);
5046
5047 fallback = false;
5048 fallbackKeyCode = AKEYCODE_UNKNOWN;
5049 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005050 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005051 }
5052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053
5054#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005055 {
5056 std::string msg;
5057 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5058 connection->inputState.getFallbackKeys();
5059 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005060 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005062 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005064 }
5065#endif
5066
5067 if (fallback) {
5068 // Restart the dispatch cycle using the fallback key.
5069 keyEntry->eventTime = event.getEventTime();
5070 keyEntry->deviceId = event.getDeviceId();
5071 keyEntry->source = event.getSource();
5072 keyEntry->displayId = event.getDisplayId();
5073 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5074 keyEntry->keyCode = fallbackKeyCode;
5075 keyEntry->scanCode = event.getScanCode();
5076 keyEntry->metaState = event.getMetaState();
5077 keyEntry->repeatCount = event.getRepeatCount();
5078 keyEntry->downTime = event.getDownTime();
5079 keyEntry->syntheticRepeat = false;
5080
5081#if DEBUG_OUTBOUND_EVENT_DETAILS
5082 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5084 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005085#endif
5086 return true; // restart the event
5087 } else {
5088#if DEBUG_OUTBOUND_EVENT_DETAILS
5089 ALOGD("Unhandled key event: No fallback key.");
5090#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005091
5092 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005093 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 }
5095 }
5096 return false;
5097}
5098
5099bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005100 DispatchEntry* dispatchEntry,
5101 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 return false;
5103}
5104
5105void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5106 mLock.unlock();
5107
5108 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5109
5110 mLock.lock();
5111}
5112
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005113KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5114 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005115 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005116 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5117 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005118 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119}
5120
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005121void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5122 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 // TODO Write some statistics about how long we spend waiting.
5124}
5125
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005126/**
5127 * Report the touch event latency to the statsd server.
5128 * Input events are reported for statistics if:
5129 * - This is a touchscreen event
5130 * - InputFilter is not enabled
5131 * - Event is not injected or synthesized
5132 *
5133 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5134 * from getting aggregated with the "old" data.
5135 */
5136void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5137 REQUIRES(mLock) {
5138 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5139 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5140 if (!reportForStatistics) {
5141 return;
5142 }
5143
5144 if (mTouchStatistics.shouldReport()) {
5145 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5146 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5147 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5148 mTouchStatistics.reset();
5149 }
5150 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5151 mTouchStatistics.addValue(latencyMicros);
5152}
5153
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154void InputDispatcher::traceInboundQueueLengthLocked() {
5155 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005156 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
5158}
5159
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005160void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 if (ATRACE_ENABLED()) {
5162 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005163 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005164 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166}
5167
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005168void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 if (ATRACE_ENABLED()) {
5170 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005171 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005172 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174}
5175
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005176void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005177 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 dumpDispatchStateLocked(dump);
5181
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005182 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005184 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186}
5187
5188void InputDispatcher::monitor() {
5189 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005190 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005192 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193}
5194
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005195/**
5196 * Wake up the dispatcher and wait until it processes all events and commands.
5197 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5198 * this method can be safely called from any thread, as long as you've ensured that
5199 * the work you are interested in completing has already been queued.
5200 */
5201bool InputDispatcher::waitForIdle() {
5202 /**
5203 * Timeout should represent the longest possible time that a device might spend processing
5204 * events and commands.
5205 */
5206 constexpr std::chrono::duration TIMEOUT = 100ms;
5207 std::unique_lock lock(mLock);
5208 mLooper->wake();
5209 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5210 return result == std::cv_status::no_timeout;
5211}
5212
Vishnu Naire798b472020-07-23 13:52:21 -07005213/**
5214 * Sets focus to the window identified by the token. This must be called
5215 * after updating any input window handles.
5216 *
5217 * Params:
5218 * request.token - input channel token used to identify the window that should gain focus.
5219 * request.focusedToken - the token that the caller expects currently to be focused. If the
5220 * specified token does not match the currently focused window, this request will be dropped.
5221 * If the specified focused token matches the currently focused window, the call will succeed.
5222 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5223 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5224 * when requesting the focus change. This determines which request gets
5225 * precedence if there is a focus change request from another source such as pointer down.
5226 */
Vishnu Nair958da932020-08-21 17:12:37 -07005227void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5228 { // acquire lock
5229 std::scoped_lock _l(mLock);
5230
5231 const int32_t displayId = request.displayId;
5232 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5233 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5234 ALOGD_IF(DEBUG_FOCUS,
5235 "setFocusedWindow on display %" PRId32
5236 " ignored, reason: focusedToken is not focused",
5237 displayId);
5238 return;
5239 }
5240
5241 mPendingFocusRequests.erase(displayId);
5242 FocusResult result = handleFocusRequestLocked(request);
5243 if (result == FocusResult::NOT_VISIBLE) {
5244 // The requested window is not currently visible. Wait for the window to become visible
5245 // and then provide it focus. This is to handle situations where a user action triggers
5246 // a new window to appear. We want to be able to queue any key events after the user
5247 // action and deliver it to the newly focused window. In order for this to happen, we
5248 // take focus from the currently focused window so key events can be queued.
5249 ALOGD_IF(DEBUG_FOCUS,
5250 "setFocusedWindow on display %" PRId32
5251 " pending, reason: window is not visible",
5252 displayId);
5253 mPendingFocusRequests[displayId] = request;
5254 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5255 "setFocusedWindow_AwaitingWindowVisibility");
5256 } else if (result != FocusResult::OK) {
5257 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5258 typeToString(result));
5259 }
5260 } // release lock
5261 // Wake up poll loop since it may need to make new input dispatching choices.
5262 mLooper->wake();
5263}
5264
5265InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5266 const FocusRequest& request) {
5267 const int32_t displayId = request.displayId;
5268 const sp<IBinder> newFocusedToken = request.token;
5269 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5270
5271 if (oldFocusedToken == request.token) {
5272 ALOGD_IF(DEBUG_FOCUS,
5273 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5274 displayId);
5275 return FocusResult::OK;
5276 }
5277
5278 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5279 if (result != FocusResult::OK) {
5280 return result;
5281 }
5282
5283 std::string_view reason =
5284 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5285 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5286 return FocusResult::OK;
5287}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005288
Vishnu Nairad321cd2020-08-20 16:40:21 -07005289void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5290 const sp<IBinder>& newFocusedToken, int32_t displayId,
5291 std::string_view reason) {
5292 if (oldFocusedToken) {
5293 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005294 if (focusedInputChannel) {
5295 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5296 "focus left window");
5297 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005298 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005299 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005300 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005301 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005302 if (newFocusedToken) {
5303 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5304 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005305 }
5306
5307 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005308 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005309 }
5310}
Vishnu Nair958da932020-08-21 17:12:37 -07005311
5312/**
5313 * Checks if the window token can be focused on a display. The token can be focused if there is
5314 * at least one window handle that is visible with the same token and all window handles with the
5315 * same token are focusable.
5316 *
5317 * In the case of mirroring, two windows may share the same window token and their visibility
5318 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5319 * we expect the focusability of the windows to match since its hard to reason why one window can
5320 * receive focus events and the other cannot when both are backed by the same input channel.
5321 */
5322InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5323 int32_t displayId) const {
5324 bool allWindowsAreFocusable = true;
5325 bool visibleWindowFound = false;
5326 bool windowFound = false;
5327 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5328 if (window->getToken() != token) {
5329 continue;
5330 }
5331 windowFound = true;
5332 if (window->getInfo()->visible) {
5333 // Check if at least a single window is visible.
5334 visibleWindowFound = true;
5335 }
5336 if (!window->getInfo()->focusable) {
5337 // Check if all windows with the window token are focusable.
5338 allWindowsAreFocusable = false;
5339 break;
5340 }
5341 }
5342
5343 if (!windowFound) {
5344 return FocusResult::NO_WINDOW;
5345 }
5346 if (!allWindowsAreFocusable) {
5347 return FocusResult::NOT_FOCUSABLE;
5348 }
5349 if (!visibleWindowFound) {
5350 return FocusResult::NOT_VISIBLE;
5351 }
5352
5353 return FocusResult::OK;
5354}
Garfield Tane84e6f92019-08-29 17:28:41 -07005355} // namespace android::inputdispatcher