blob: a10da66de4a7b1de12c77b217f7fcf708f5a891f [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
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;
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -0500415 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 &&
1111 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.
1116 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1117 resetKeyRepeatLocked();
1118 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1119 } else {
1120 // Not a repeat. Save key down state in case we do see a repeat later.
1121 resetKeyRepeatLocked();
1122 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1123 }
1124 mKeyRepeatState.lastKeyEntry = entry;
1125 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 resetKeyRepeatLocked();
1128 }
1129
1130 if (entry->repeatCount == 1) {
1131 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1132 } else {
1133 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1134 }
1135
1136 entry->dispatchInProgress = true;
1137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001138 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
1140
1141 // Handle case where the policy asked us to try again later last time.
1142 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1143 if (currentTime < entry->interceptKeyWakeupTime) {
1144 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1145 *nextWakeupTime = entry->interceptKeyWakeupTime;
1146 }
1147 return false; // wait until next wakeup
1148 }
1149 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1150 entry->interceptKeyWakeupTime = 0;
1151 }
1152
1153 // Give the policy a chance to intercept the key.
1154 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1155 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001156 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001157 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001158 sp<IBinder> focusedWindowToken =
1159 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1160 if (focusedWindowToken != nullptr) {
1161 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001164 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 entry->refCount += 1;
1166 return false; // wait for the command to run
1167 } else {
1168 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1169 }
1170 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001171 if (*dropReason == DropReason::NOT_DROPPED) {
1172 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
1174 }
1175
1176 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001177 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001179 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001181 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return true;
1183 }
1184
1185 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001186 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1190 return false;
1191 }
1192
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001193 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1195 return true;
1196 }
1197
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001198 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001199 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200
1201 // Dispatch the key.
1202 dispatchEventLocked(currentTime, entry, inputTargets);
1203 return true;
1204}
1205
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001206void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001208 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1210 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1212 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1213 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214#endif
1215}
1216
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1218 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001219 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 entry->dispatchInProgress = true;
1223
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001224 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
1226
1227 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001230 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 return true;
1233 }
1234
1235 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1236
1237 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001238 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239
1240 bool conflictingPointerActions = false;
1241 int32_t injectionResult;
1242 if (isPointerEvent) {
1243 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001245 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 } else {
1248 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001250 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 }
1252 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1253 return false;
1254 }
1255
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001256 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001257 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1258 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1259 return true;
1260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001262 CancelationOptions::Mode mode(isPointerEvent
1263 ? CancelationOptions::CANCEL_POINTER_EVENTS
1264 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1265 CancelationOptions options(mode, "input event injection failed");
1266 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 return true;
1268 }
1269
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001270 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001271 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001273 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001274 std::unordered_map<int32_t, TouchState>::iterator it =
1275 mTouchStatesByDisplay.find(entry->displayId);
1276 if (it != mTouchStatesByDisplay.end()) {
1277 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001278 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001279 // The event has gone through these portal windows, so we add monitoring targets of
1280 // the corresponding displays as well.
1281 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001282 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001283 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001285 }
1286 }
1287 }
1288 }
1289
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 // Dispatch the motion.
1291 if (conflictingPointerActions) {
1292 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 synthesizeCancelationEventsForAllConnectionsLocked(options);
1295 }
1296 dispatchEventLocked(currentTime, entry, inputTargets);
1297 return true;
1298}
1299
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001302 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 ", policyFlags=0x%x, "
1304 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1305 "metaState=0x%x, buttonState=0x%x,"
1306 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001307 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1308 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1309 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001311 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 "x=%f, y=%f, pressure=%f, size=%f, "
1314 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1315 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001316 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1317 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1318 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1319 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1320 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1321 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1322 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1323 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1324 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1325 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
1327#endif
1328}
1329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1331 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001332 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333#if DEBUG_DISPATCH_CYCLE
1334 ALOGD("dispatchEventToCurrentInputTargets");
1335#endif
1336
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001337 updateInteractionTokensLocked(*eventEntry, inputTargets);
1338
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1340
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001341 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001343 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001344 sp<Connection> connection =
1345 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001346 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001347 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001349 if (DEBUG_FOCUS) {
1350 ALOGD("Dropping event delivery to target with channel '%s' because it "
1351 "is no longer registered with the input dispatcher.",
1352 inputTarget.inputChannel->getName().c_str());
1353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 }
1355 }
1356}
1357
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001358void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1359 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1360 // If the policy decides to close the app, we will get a channel removal event via
1361 // unregisterInputChannel, and will clean up the connection that way. We are already not
1362 // sending new pointers to the connection when it blocked, but focused events will continue to
1363 // pile up.
1364 ALOGW("Canceling events for %s because it is unresponsive",
1365 connection->inputChannel->getName().c_str());
1366 if (connection->status == Connection::STATUS_NORMAL) {
1367 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1368 "application not responding");
1369 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 }
1371}
1372
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001373void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001374 if (DEBUG_FOCUS) {
1375 ALOGD("Resetting ANR timeouts.");
1376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
1378 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001379 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001380 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Tiger Huang721e26f2018-07-24 22:26:19 +08001383/**
1384 * Get the display id that the given event should go to. If this event specifies a valid display id,
1385 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1386 * Focused display is the display that the user most recently interacted with.
1387 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001389 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001390 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001391 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1393 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 break;
1395 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001396 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001397 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1398 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001399 break;
1400 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001401 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001402 case EventEntry::Type::CONFIGURATION_CHANGED:
1403 case EventEntry::Type::DEVICE_RESET: {
1404 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001405 return ADISPLAY_ID_NONE;
1406 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001407 }
1408 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1409}
1410
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001411bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1412 const char* focusedWindowName) {
1413 if (mAnrTracker.empty()) {
1414 // already processed all events that we waited for
1415 mKeyIsWaitingForEventsTimeout = std::nullopt;
1416 return false;
1417 }
1418
1419 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1420 // Start the timer
1421 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1422 "focus to change",
1423 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001424 mKeyIsWaitingForEventsTimeout = currentTime +
1425 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1426 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001427 return true;
1428 }
1429
1430 // We still have pending events, and already started the timer
1431 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1432 return true; // Still waiting
1433 }
1434
1435 // Waited too long, and some connection still hasn't processed all motions
1436 // Just send the key to the focused window
1437 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1438 focusedWindowName);
1439 mKeyIsWaitingForEventsTimeout = std::nullopt;
1440 return false;
1441}
1442
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 std::vector<InputTarget>& inputTargets,
1446 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001447 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
Tiger Huang721e26f2018-07-24 22:26:19 +08001449 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001450 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001451 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001452 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1453
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 // If there is no currently focused window and no focused application
1455 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001456 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1457 ALOGI("Dropping %s event because there is no focused window or focused application in "
1458 "display %" PRId32 ".",
1459 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001460 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 }
1462
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1464 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1465 // start interacting with another application via touch (app switch). This code can be removed
1466 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1467 // an app is expected to have a focused window.
1468 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1469 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1470 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001471 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1472 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1473 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001474 mAwaitedFocusedApplication = focusedApplicationHandle;
1475 ALOGW("Waiting because no window has focus but %s may eventually add a "
1476 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001477 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001478 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1479 return INPUT_EVENT_INJECTION_PENDING;
1480 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1481 // Already raised ANR. Drop the event
1482 ALOGE("Dropping %s event because there is no focused window",
1483 EventEntry::typeToString(entry.type));
1484 return INPUT_EVENT_INJECTION_FAILED;
1485 } else {
1486 // Still waiting for the focused window
1487 return INPUT_EVENT_INJECTION_PENDING;
1488 }
1489 }
1490
1491 // we have a valid, non-null focused window
1492 resetNoFocusedWindowTimeoutLocked();
1493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001495 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001496 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 }
1498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001499 if (focusedWindowHandle->getInfo()->paused) {
1500 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1501 return INPUT_EVENT_INJECTION_PENDING;
1502 }
1503
1504 // If the event is a key event, then we must wait for all previous events to
1505 // complete before delivering it because previous events may have the
1506 // side-effect of transferring focus to a different window and we want to
1507 // ensure that the following keys are sent to the new window.
1508 //
1509 // Suppose the user touches a button in a window then immediately presses "A".
1510 // If the button causes a pop-up window to appear then we want to ensure that
1511 // the "A" key is delivered to the new pop-up window. This is because users
1512 // often anticipate pending UI changes when typing on a keyboard.
1513 // To obtain this behavior, we must serialize key events with respect to all
1514 // prior input events.
1515 if (entry.type == EventEntry::Type::KEY) {
1516 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1517 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1518 return INPUT_EVENT_INJECTION_PENDING;
1519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 }
1521
1522 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001523 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1525 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526
1527 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001528 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529}
1530
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001531/**
1532 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1533 * that are currently unresponsive.
1534 */
1535std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1536 const std::vector<TouchedMonitor>& monitors) const {
1537 std::vector<TouchedMonitor> responsiveMonitors;
1538 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1539 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1540 sp<Connection> connection = getConnectionLocked(
1541 monitor.monitor.inputChannel->getConnectionToken());
1542 if (connection == nullptr) {
1543 ALOGE("Could not find connection for monitor %s",
1544 monitor.monitor.inputChannel->getName().c_str());
1545 return false;
1546 }
1547 if (!connection->responsive) {
1548 ALOGW("Unresponsive monitor %s will not get the new gesture",
1549 connection->inputChannel->getName().c_str());
1550 return false;
1551 }
1552 return true;
1553 });
1554 return responsiveMonitors;
1555}
1556
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001558 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 std::vector<InputTarget>& inputTargets,
1560 nsecs_t* nextWakeupTime,
1561 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001562 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 enum InjectionPermission {
1564 INJECTION_PERMISSION_UNKNOWN,
1565 INJECTION_PERMISSION_GRANTED,
1566 INJECTION_PERMISSION_DENIED
1567 };
1568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 // For security reasons, we defer updating the touch state until we are sure that
1570 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001571 int32_t displayId = entry.displayId;
1572 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1574
1575 // Update the touch state as needed based on the properties of the touch event.
1576 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1577 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001578 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1579 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001581 // Copy current touch state into tempTouchState.
1582 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1583 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001584 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001585 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001586 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1587 mTouchStatesByDisplay.find(displayId);
1588 if (oldStateIt != mTouchStatesByDisplay.end()) {
1589 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001590 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001591 }
1592
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001593 bool isSplit = tempTouchState.split;
1594 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1595 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1596 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1598 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1599 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1600 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1601 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001602 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 bool wrongDevice = false;
1604 if (newGesture) {
1605 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001606 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001607 ALOGI("Dropping event because a pointer for a different device is already down "
1608 "in display %" PRId32,
1609 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001610 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1612 switchedDevice = false;
1613 wrongDevice = true;
1614 goto Failed;
1615 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001616 tempTouchState.reset();
1617 tempTouchState.down = down;
1618 tempTouchState.deviceId = entry.deviceId;
1619 tempTouchState.source = entry.source;
1620 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001622 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001623 ALOGI("Dropping move event because a pointer for a different device is already active "
1624 "in display %" PRId32,
1625 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001626 // TODO: test multiple simultaneous input streams.
1627 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1628 switchedDevice = false;
1629 wrongDevice = true;
1630 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 }
1632
1633 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1634 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1635
Garfield Tan00f511d2019-06-12 16:55:40 -07001636 int32_t x;
1637 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001639 // Always dispatch mouse events to cursor position.
1640 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641 x = int32_t(entry.xCursorPosition);
1642 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001643 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1645 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001646 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001647 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001648 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001649 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1650 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001651
1652 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001653 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001654 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 if (newTouchedWindowHandle != nullptr &&
1658 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001659 // New window supports splitting, but we should never split mouse events.
1660 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 } else if (isSplit) {
1662 // New window does not support splitting but we have already split events.
1663 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001664 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 }
1666
1667 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001668 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001670 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001671 }
1672
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001673 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1674 ALOGI("Not sending touch event to %s because it is paused",
1675 newTouchedWindowHandle->getName().c_str());
1676 newTouchedWindowHandle = nullptr;
1677 }
1678
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001679 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001680 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001681 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1682 if (!isResponsive) {
1683 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001684 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1685 newTouchedWindowHandle = nullptr;
1686 }
1687 }
1688
1689 // Also don't send the new touch event to unresponsive gesture monitors
1690 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1691
Michael Wright3dd60e22019-03-27 22:06:44 +00001692 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1693 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001694 "(%d, %d) in display %" PRId32 ".",
1695 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001696 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1697 goto Failed;
1698 }
1699
1700 if (newTouchedWindowHandle != nullptr) {
1701 // Set target flags.
1702 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1703 if (isSplit) {
1704 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1707 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1708 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1709 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1710 }
1711
1712 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001713 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1714 newHoverWindowHandle = nullptr;
1715 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001716 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001717 }
1718
1719 // Update the temporary touch state.
1720 BitSet32 pointerIds;
1721 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001722 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 pointerIds.markBit(pointerId);
1724 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001725 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 }
1727
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001728 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 } else {
1730 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1731
1732 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001733 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001734 if (DEBUG_FOCUS) {
1735 ALOGD("Dropping event because the pointer is not down or we previously "
1736 "dropped the pointer down event in display %" PRId32,
1737 displayId);
1738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1740 goto Failed;
1741 }
1742
1743 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001745 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001746 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1747 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001750 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001751 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1753 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001754 if (DEBUG_FOCUS) {
1755 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1756 oldTouchedWindowHandle->getName().c_str(),
1757 newTouchedWindowHandle->getName().c_str(), displayId);
1758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001760 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1761 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1762 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
1764 // Make a slippery entrance into the new window.
1765 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1766 isSplit = true;
1767 }
1768
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001769 int32_t targetFlags =
1770 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (isSplit) {
1772 targetFlags |= InputTarget::FLAG_SPLIT;
1773 }
1774 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1775 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1776 }
1777
1778 BitSet32 pointerIds;
1779 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001782 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 }
1784 }
1785 }
1786
1787 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001788 // Let the previous window know that the hover sequence is over, unless we already did it
1789 // when dispatching it as is to newTouchedWindowHandle.
1790 if (mLastHoverWindowHandle != nullptr &&
1791 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1792 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793#if DEBUG_HOVER
1794 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001797 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1798 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800
Garfield Tandf26e862020-07-01 20:18:19 -07001801 // Let the new window know that the hover sequence is starting, unless we already did it
1802 // when dispatching it as is to newTouchedWindowHandle.
1803 if (newHoverWindowHandle != nullptr &&
1804 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1805 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#if DEBUG_HOVER
1807 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1811 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1812 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 }
1814 }
1815
1816 // Check permission to inject into all touched foreground windows and ensure there
1817 // is at least one touched foreground window.
1818 {
1819 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001820 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1822 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001823 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1825 injectionPermission = INJECTION_PERMISSION_DENIED;
1826 goto Failed;
1827 }
1828 }
1829 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001831 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001832 ALOGI("Dropping event because there is no touched foreground window in display "
1833 "%" PRId32 " or gesture monitor to receive it.",
1834 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1836 goto Failed;
1837 }
1838
1839 // Permission granted to injection into all touched foreground windows.
1840 injectionPermission = INJECTION_PERMISSION_GRANTED;
1841 }
1842
1843 // Check whether windows listening for outside touches are owned by the same UID. If it is
1844 // set the policy flag that we will not reveal coordinate information to this window.
1845 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1846 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001848 if (foregroundWindowHandle) {
1849 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001851 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1852 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1853 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001854 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1855 InputTarget::FLAG_ZERO_COORDS,
1856 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859 }
1860 }
1861 }
1862
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 // If this is the first pointer going down and the touched window has a wallpaper
1864 // then also add the touched wallpaper windows so they are locked in for the duration
1865 // of the touch gesture.
1866 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1867 // engine only supports touch events. We would need to add a mechanism similar
1868 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1869 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1870 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001871 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001872 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001873 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001874 getWindowHandlesLocked(displayId);
1875 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001877 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001878 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001879 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 .addOrUpdateWindow(windowHandle,
1881 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1882 InputTarget::
1883 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1884 InputTarget::FLAG_DISPATCH_AS_IS,
1885 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
1887 }
1888 }
1889 }
1890
1891 // Success! Output targets.
1892 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1893
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001896 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001899 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001900 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001901 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001902 }
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 // Drop the outside or hover touch windows since we will not care about them
1905 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001906 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907
1908Failed:
1909 // Check injection permission once and for all.
1910 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001911 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 injectionPermission = INJECTION_PERMISSION_GRANTED;
1913 } else {
1914 injectionPermission = INJECTION_PERMISSION_DENIED;
1915 }
1916 }
1917
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001918 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1919 return injectionResult;
1920 }
1921
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001923 if (!wrongDevice) {
1924 if (switchedDevice) {
1925 if (DEBUG_FOCUS) {
1926 ALOGD("Conflicting pointer actions: Switched to a different device.");
1927 }
1928 *outConflictingPointerActions = true;
1929 }
1930
1931 if (isHoverAction) {
1932 // Started hovering, therefore no longer down.
1933 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001934 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001935 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1936 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 *outConflictingPointerActions = true;
1939 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001940 tempTouchState.reset();
1941 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1942 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1943 tempTouchState.deviceId = entry.deviceId;
1944 tempTouchState.source = entry.source;
1945 tempTouchState.displayId = displayId;
1946 }
1947 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1948 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1949 // All pointers up or canceled.
1950 tempTouchState.reset();
1951 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1952 // First pointer went down.
1953 if (oldState && oldState->down) {
1954 if (DEBUG_FOCUS) {
1955 ALOGD("Conflicting pointer actions: Down received while already down.");
1956 }
1957 *outConflictingPointerActions = true;
1958 }
1959 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1960 // One pointer went up.
1961 if (isSplit) {
1962 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1963 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001965 for (size_t i = 0; i < tempTouchState.windows.size();) {
1966 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1967 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1968 touchedWindow.pointerIds.clearBit(pointerId);
1969 if (touchedWindow.pointerIds.isEmpty()) {
1970 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1971 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001974 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001976 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001977 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001978
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001979 // Save changes unless the action was scroll in which case the temporary touch
1980 // state was only valid for this one action.
1981 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1982 if (tempTouchState.displayId >= 0) {
1983 mTouchStatesByDisplay[displayId] = tempTouchState;
1984 } else {
1985 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001989 // Update hover state.
1990 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 return injectionResult;
1994}
1995
1996void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001997 int32_t targetFlags, BitSet32 pointerIds,
1998 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001999 std::vector<InputTarget>::iterator it =
2000 std::find_if(inputTargets.begin(), inputTargets.end(),
2001 [&windowHandle](const InputTarget& inputTarget) {
2002 return inputTarget.inputChannel->getConnectionToken() ==
2003 windowHandle->getToken();
2004 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002005
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002006 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002007
2008 if (it == inputTargets.end()) {
2009 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002010 std::shared_ptr<InputChannel> inputChannel =
2011 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002012 if (inputChannel == nullptr) {
2013 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2014 return;
2015 }
2016 inputTarget.inputChannel = inputChannel;
2017 inputTarget.flags = targetFlags;
2018 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2019 inputTargets.push_back(inputTarget);
2020 it = inputTargets.end() - 1;
2021 }
2022
2023 ALOG_ASSERT(it->flags == targetFlags);
2024 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2025
chaviw1ff3d1e2020-07-01 15:53:47 -07002026 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027}
2028
Michael Wright3dd60e22019-03-27 22:06:44 +00002029void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 int32_t displayId, float xOffset,
2031 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002032 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2033 mGlobalMonitorsByDisplay.find(displayId);
2034
2035 if (it != mGlobalMonitorsByDisplay.end()) {
2036 const std::vector<Monitor>& monitors = it->second;
2037 for (const Monitor& monitor : monitors) {
2038 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
2041}
2042
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2044 float yOffset,
2045 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002046 InputTarget target;
2047 target.inputChannel = monitor.inputChannel;
2048 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002049 ui::Transform t;
2050 t.set(xOffset, yOffset);
2051 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002052 inputTargets.push_back(target);
2053}
2054
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 const InjectionState* injectionState) {
2057 if (injectionState &&
2058 (windowHandle == nullptr ||
2059 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2060 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002061 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 "owned by uid %d",
2064 injectionState->injectorPid, injectionState->injectorUid,
2065 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 } else {
2067 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070 return false;
2071 }
2072 return true;
2073}
2074
Robert Carrc9bf1d32020-04-13 17:21:08 -07002075/**
2076 * Indicate whether one window handle should be considered as obscuring
2077 * another window handle. We only check a few preconditions. Actually
2078 * checking the bounds is left to the caller.
2079 */
2080static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2081 const sp<InputWindowHandle>& otherHandle) {
2082 // Compare by token so cloned layers aren't counted
2083 if (haveSameToken(windowHandle, otherHandle)) {
2084 return false;
2085 }
2086 auto info = windowHandle->getInfo();
2087 auto otherInfo = otherHandle->getInfo();
2088 if (!otherInfo->visible) {
2089 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002090 } else if (info->ownerPid == otherInfo->ownerPid) {
2091 // If ownerPid is the same we don't generate occlusion events as there
2092 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002093 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002094 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002095 return false;
2096 } else if (otherInfo->displayId != info->displayId) {
2097 return false;
2098 }
2099 return true;
2100}
2101
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2103 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002105 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002106 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002107 if (windowHandle == otherHandle) {
2108 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002111 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002112 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 return true;
2114 }
2115 }
2116 return false;
2117}
2118
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002119bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2120 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002121 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002122 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002123 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002124 if (windowHandle == otherHandle) {
2125 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002126 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002127 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002128 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002129 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002130 return true;
2131 }
2132 }
2133 return false;
2134}
2135
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002136std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002137 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002139 if (applicationHandle != nullptr) {
2140 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002141 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 } else {
2143 return applicationHandle->getName();
2144 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002145 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002146 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002148 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150}
2151
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002152void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002153 if (eventEntry.type == EventEntry::Type::FOCUS) {
2154 // Focus events are passed to apps, but do not represent user activity.
2155 return;
2156 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002157 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002158 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002159 if (focusedWindowHandle != nullptr) {
2160 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002161 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002163 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164#endif
2165 return;
2166 }
2167 }
2168
2169 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002170 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002171 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2173 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 return;
2175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002177 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 eventType = USER_ACTIVITY_EVENT_TOUCH;
2179 }
2180 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002182 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2184 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002185 return;
2186 }
2187 eventType = USER_ACTIVITY_EVENT_BUTTON;
2188 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002190 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002191 case EventEntry::Type::CONFIGURATION_CHANGED:
2192 case EventEntry::Type::DEVICE_RESET: {
2193 LOG_ALWAYS_FATAL("%s events are not user activity",
2194 EventEntry::typeToString(eventEntry.type));
2195 break;
2196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002199 std::unique_ptr<CommandEntry> commandEntry =
2200 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002201 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002203 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204}
2205
2206void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002207 const sp<Connection>& connection,
2208 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002209 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002210 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002211 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002212 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002213 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 ATRACE_NAME(message.c_str());
2215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216#if DEBUG_DISPATCH_CYCLE
2217 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002218 "globalScaleFactor=%f, pointerIds=0x%x %s",
2219 connection->getInputChannelName().c_str(), inputTarget.flags,
2220 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2221 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222#endif
2223
2224 // Skip this event if the connection status is not normal.
2225 // We don't want to enqueue additional outbound events if the connection is broken.
2226 if (connection->status != Connection::STATUS_NORMAL) {
2227#if DEBUG_DISPATCH_CYCLE
2228 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230#endif
2231 return;
2232 }
2233
2234 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002235 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2236 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2237 "Entry type %s should not have FLAG_SPLIT",
2238 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002240 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002241 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002242 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002243 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 if (!splitMotionEntry) {
2245 return; // split event was dropped
2246 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002247 if (DEBUG_FOCUS) {
2248 ALOGD("channel '%s' ~ Split motion event.",
2249 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002250 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002251 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 splitMotionEntry->release();
2254 return;
2255 }
2256 }
2257
2258 // Not splitting. Enqueue dispatch entries for the event as is.
2259 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2260}
2261
2262void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263 const sp<Connection>& connection,
2264 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002265 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002266 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002268 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002269 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002270 ATRACE_NAME(message.c_str());
2271 }
2272
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002273 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274
2275 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002276 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288
2289 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002290 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 startDispatchCycleLocked(currentTime, connection);
2292 }
2293}
2294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2296 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002297 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002299 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2301 connection->getInputChannelName().c_str(),
2302 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 ATRACE_NAME(message.c_str());
2304 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002305 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 if (!(inputTargetFlags & dispatchMode)) {
2307 return;
2308 }
2309 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2310
2311 // This is a new event.
2312 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002313 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002314 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002316 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2317 // different EventEntry than what was passed in.
2318 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002320 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002321 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002322 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002323 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002324 dispatchEntry->resolvedAction = keyEntry.action;
2325 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2328 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2331 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 return; // skip the inconsistent event
2334 }
2335 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002338 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002339 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002340 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2341 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2342 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2343 static_cast<int32_t>(IdGenerator::Source::OTHER);
2344 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2346 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2347 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2349 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2351 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2355 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002356 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002357 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 }
2359 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002360 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2361 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002363 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2364 "event",
2365 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002370 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002371 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2372 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2373 }
2374 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2375 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002378 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2379 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2382 "event",
2383 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 return; // skip the inconsistent event
2386 }
2387
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002388 dispatchEntry->resolvedEventId =
2389 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2390 ? mIdGenerator.nextId()
2391 : motionEntry.id;
2392 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2393 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2394 ") to MotionEvent(id=0x%" PRIx32 ").",
2395 motionEntry.id, dispatchEntry->resolvedEventId);
2396 ATRACE_NAME(message.c_str());
2397 }
2398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002399 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002400 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002401
2402 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002404 case EventEntry::Type::FOCUS: {
2405 break;
2406 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002407 case EventEntry::Type::CONFIGURATION_CHANGED:
2408 case EventEntry::Type::DEVICE_RESET: {
2409 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002410 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002411 break;
2412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414
2415 // Remember that we are waiting for this dispatch to complete.
2416 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002417 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 }
2419
2420 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002421 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002422 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002423}
2424
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002425/**
2426 * This function is purely for debugging. It helps us understand where the user interaction
2427 * was taking place. For example, if user is touching launcher, we will see a log that user
2428 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2429 * We will see both launcher and wallpaper in that list.
2430 * Once the interaction with a particular set of connections starts, no new logs will be printed
2431 * until the set of interacted connections changes.
2432 *
2433 * The following items are skipped, to reduce the logspam:
2434 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2435 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2436 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2437 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2438 * Both of those ACTION_UP events would not be logged
2439 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2440 * will not be logged. This is omitted to reduce the amount of data printed.
2441 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2442 * gesture monitor is the only connection receiving the remainder of the gesture.
2443 */
2444void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2445 const std::vector<InputTarget>& targets) {
2446 // Skip ACTION_UP events, and all events other than keys and motions
2447 if (entry.type == EventEntry::Type::KEY) {
2448 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2449 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2450 return;
2451 }
2452 } else if (entry.type == EventEntry::Type::MOTION) {
2453 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2454 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2455 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2456 return;
2457 }
2458 } else {
2459 return; // Not a key or a motion
2460 }
2461
2462 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2463 std::vector<sp<Connection>> newConnections;
2464 for (const InputTarget& target : targets) {
2465 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2466 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2467 continue; // Skip windows that receive ACTION_OUTSIDE
2468 }
2469
2470 sp<IBinder> token = target.inputChannel->getConnectionToken();
2471 sp<Connection> connection = getConnectionLocked(token);
2472 if (connection == nullptr || connection->monitor) {
2473 continue; // We only need to keep track of the non-monitor connections.
2474 }
2475 newConnectionTokens.insert(std::move(token));
2476 newConnections.emplace_back(connection);
2477 }
2478 if (newConnectionTokens == mInteractionConnectionTokens) {
2479 return; // no change
2480 }
2481 mInteractionConnectionTokens = newConnectionTokens;
2482
2483 std::string windowList;
2484 for (const sp<Connection>& connection : newConnections) {
2485 windowList += connection->getWindowName() + ", ";
2486 }
2487 std::string message = "Interaction with windows: " + windowList;
2488 if (windowList.empty()) {
2489 message += "<none>";
2490 }
2491 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2492}
2493
chaviwfd6d3512019-03-25 13:23:49 -07002494void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002495 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002496 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002497 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2498 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002499 return;
2500 }
2501
Vishnu Nairad321cd2020-08-20 16:40:21 -07002502 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2503 if (focusedToken == token) {
2504 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002505 return;
2506 }
2507
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2509 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002510 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002511 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512}
2513
2514void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002515 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002516 if (ATRACE_ENABLED()) {
2517 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002519 ATRACE_NAME(message.c_str());
2520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523#endif
2524
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002525 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2526 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002528 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002529 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002530 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531
2532 // Publish the event.
2533 status_t status;
2534 EventEntry* eventEntry = dispatchEntry->eventEntry;
2535 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002536 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002537 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2538 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002541 status =
2542 connection->inputPublisher
2543 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2544 keyEntry->deviceId, keyEntry->source,
2545 keyEntry->displayId, std::move(hmac),
2546 dispatchEntry->resolvedAction,
2547 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2548 keyEntry->scanCode, keyEntry->metaState,
2549 keyEntry->repeatCount, keyEntry->downTime,
2550 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 }
2553
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002554 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 PointerCoords scaledCoords[MAX_POINTERS];
2558 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2559
chaviw82357092020-01-28 13:13:06 -08002560 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2562 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2563 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002564 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002565 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2566 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002567 // Don't apply window scale here since we don't want scale to affect raw
2568 // coordinates. The scale will be sent back to the client and applied
2569 // later when requesting relative coordinates.
2570 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2571 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002572 }
2573 usingCoords = scaledCoords;
2574 }
2575 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 // We don't want the dispatch target to know.
2577 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2578 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2579 scaledCoords[i].clear();
2580 }
2581 usingCoords = scaledCoords;
2582 }
2583 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002584
2585 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586
2587 // Publish the motion event.
2588 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002589 .publishMotionEvent(dispatchEntry->seq,
2590 dispatchEntry->resolvedEventId,
2591 motionEntry->deviceId, motionEntry->source,
2592 motionEntry->displayId, std::move(hmac),
2593 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 motionEntry->actionButton,
2595 dispatchEntry->resolvedFlags,
2596 motionEntry->edgeFlags, motionEntry->metaState,
2597 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002598 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002599 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002600 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002601 motionEntry->yPrecision,
2602 motionEntry->xCursorPosition,
2603 motionEntry->yCursorPosition,
2604 motionEntry->downTime, motionEntry->eventTime,
2605 motionEntry->pointerCount,
2606 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002607 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 break;
2609 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002610 case EventEntry::Type::FOCUS: {
2611 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2612 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002613 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002614 focusEntry->hasFocus,
2615 mInTouchMode);
2616 break;
2617 }
2618
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002619 case EventEntry::Type::CONFIGURATION_CHANGED:
2620 case EventEntry::Type::DEVICE_RESET: {
2621 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2622 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 }
2626
2627 // Check the result.
2628 if (status) {
2629 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002630 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002632 "This is unexpected because the wait queue is empty, so the pipe "
2633 "should be empty and we shouldn't have any problems writing an "
2634 "event to it, status=%d",
2635 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2637 } else {
2638 // Pipe is full and we are waiting for the app to finish process some events
2639 // before sending more events to it.
2640#if DEBUG_DISPATCH_CYCLE
2641 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 "waiting for the application to catch up",
2643 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 }
2646 } else {
2647 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 "status=%d",
2649 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2651 }
2652 return;
2653 }
2654
2655 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002656 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2657 connection->outboundQueue.end(),
2658 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002659 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002660 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002661 if (connection->responsive) {
2662 mAnrTracker.insert(dispatchEntry->timeoutTime,
2663 connection->inputChannel->getConnectionToken());
2664 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002665 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 }
2667}
2668
chaviw09c8d2d2020-08-24 15:48:26 -07002669std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2670 size_t size;
2671 switch (event.type) {
2672 case VerifiedInputEvent::Type::KEY: {
2673 size = sizeof(VerifiedKeyEvent);
2674 break;
2675 }
2676 case VerifiedInputEvent::Type::MOTION: {
2677 size = sizeof(VerifiedMotionEvent);
2678 break;
2679 }
2680 }
2681 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2682 return mHmacKeyManager.sign(start, size);
2683}
2684
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002685const std::array<uint8_t, 32> InputDispatcher::getSignature(
2686 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2687 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2688 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2689 // Only sign events up and down events as the purely move events
2690 // are tied to their up/down counterparts so signing would be redundant.
2691 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2692 verifiedEvent.actionMasked = actionMasked;
2693 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002694 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002695 }
2696 return INVALID_HMAC;
2697}
2698
2699const std::array<uint8_t, 32> InputDispatcher::getSignature(
2700 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2701 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2702 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2703 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002704 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002705}
2706
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002708 const sp<Connection>& connection, uint32_t seq,
2709 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710#if DEBUG_DISPATCH_CYCLE
2711 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002712 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713#endif
2714
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 if (connection->status == Connection::STATUS_BROKEN ||
2716 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 return;
2718 }
2719
2720 // Notify other system components and prepare to start the next dispatch cycle.
2721 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2722}
2723
2724void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 const sp<Connection>& connection,
2726 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#if DEBUG_DISPATCH_CYCLE
2728 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730#endif
2731
2732 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002733 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002734 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002735 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002736 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
2738 // The connection appears to be unrecoverably broken.
2739 // Ignore already broken or zombie connections.
2740 if (connection->status == Connection::STATUS_NORMAL) {
2741 connection->status = Connection::STATUS_BROKEN;
2742
2743 if (notify) {
2744 // Notify other system components.
2745 onDispatchCycleBrokenLocked(currentTime, connection);
2746 }
2747 }
2748}
2749
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002750void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2751 while (!queue.empty()) {
2752 DispatchEntry* dispatchEntry = queue.front();
2753 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002754 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756}
2757
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002758void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002760 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 }
2762 delete dispatchEntry;
2763}
2764
2765int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2766 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2767
2768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002769 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002771 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 "fd=%d, events=0x%x",
2774 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 return 0; // remove the callback
2776 }
2777
2778 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2781 if (!(events & ALOOPER_EVENT_INPUT)) {
2782 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 "events=0x%x",
2784 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 return 1;
2786 }
2787
2788 nsecs_t currentTime = now();
2789 bool gotOne = false;
2790 status_t status;
2791 for (;;) {
2792 uint32_t seq;
2793 bool handled;
2794 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2795 if (status) {
2796 break;
2797 }
2798 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2799 gotOne = true;
2800 }
2801 if (gotOne) {
2802 d->runCommandsLockedInterruptible();
2803 if (status == WOULD_BLOCK) {
2804 return 1;
2805 }
2806 }
2807
2808 notify = status != DEAD_OBJECT || !connection->monitor;
2809 if (notify) {
2810 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813 } else {
2814 // Monitor channels are never explicitly unregistered.
2815 // We do it automatically when the remote endpoint is closed so don't warn
2816 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002817 const bool stillHaveWindowHandle =
2818 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2819 nullptr;
2820 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 if (notify) {
2822 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 "events=0x%x",
2824 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826 }
2827
2828 // Unregister the channel.
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05002829 d->unregisterInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832}
2833
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002836 for (const auto& pair : mConnectionsByFd) {
2837 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839}
2840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002842 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002843 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2844 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2845}
2846
2847void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2848 const CancelationOptions& options,
2849 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2850 for (const auto& it : monitorsByDisplay) {
2851 const std::vector<Monitor>& monitors = it.second;
2852 for (const Monitor& monitor : monitors) {
2853 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002854 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002855 }
2856}
2857
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002859 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002860 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002861 if (connection == nullptr) {
2862 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002864
2865 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866}
2867
2868void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2869 const sp<Connection>& connection, const CancelationOptions& options) {
2870 if (connection->status == Connection::STATUS_BROKEN) {
2871 return;
2872 }
2873
2874 nsecs_t currentTime = now();
2875
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002876 std::vector<EventEntry*> cancelationEvents =
2877 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002879 if (cancelationEvents.empty()) {
2880 return;
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002883 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2884 "with reality: %s, mode=%d.",
2885 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2886 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002888
2889 InputTarget target;
2890 sp<InputWindowHandle> windowHandle =
2891 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2892 if (windowHandle != nullptr) {
2893 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002894 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002895 target.globalScaleFactor = windowInfo->globalScaleFactor;
2896 }
2897 target.inputChannel = connection->inputChannel;
2898 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2899
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002900 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2901 EventEntry* cancelationEventEntry = cancelationEvents[i];
2902 switch (cancelationEventEntry->type) {
2903 case EventEntry::Type::KEY: {
2904 logOutboundKeyDetails("cancel - ",
2905 static_cast<const KeyEntry&>(*cancelationEventEntry));
2906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002908 case EventEntry::Type::MOTION: {
2909 logOutboundMotionDetails("cancel - ",
2910 static_cast<const MotionEntry&>(*cancelationEventEntry));
2911 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002913 case EventEntry::Type::FOCUS: {
2914 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2915 break;
2916 }
2917 case EventEntry::Type::CONFIGURATION_CHANGED:
2918 case EventEntry::Type::DEVICE_RESET: {
2919 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2920 EventEntry::typeToString(cancelationEventEntry->type));
2921 break;
2922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 }
2924
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002925 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2926 target, InputTarget::FLAG_DISPATCH_AS_IS);
2927
2928 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002930
2931 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932}
2933
Svet Ganov5d3bc372020-01-26 23:11:07 -08002934void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2935 const sp<Connection>& connection) {
2936 if (connection->status == Connection::STATUS_BROKEN) {
2937 return;
2938 }
2939
2940 nsecs_t currentTime = now();
2941
2942 std::vector<EventEntry*> downEvents =
2943 connection->inputState.synthesizePointerDownEvents(currentTime);
2944
2945 if (downEvents.empty()) {
2946 return;
2947 }
2948
2949#if DEBUG_OUTBOUND_EVENT_DETAILS
2950 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2951 connection->getInputChannelName().c_str(), downEvents.size());
2952#endif
2953
2954 InputTarget target;
2955 sp<InputWindowHandle> windowHandle =
2956 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2957 if (windowHandle != nullptr) {
2958 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002959 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002960 target.globalScaleFactor = windowInfo->globalScaleFactor;
2961 }
2962 target.inputChannel = connection->inputChannel;
2963 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2964
2965 for (EventEntry* downEventEntry : downEvents) {
2966 switch (downEventEntry->type) {
2967 case EventEntry::Type::MOTION: {
2968 logOutboundMotionDetails("down - ",
2969 static_cast<const MotionEntry&>(*downEventEntry));
2970 break;
2971 }
2972
2973 case EventEntry::Type::KEY:
2974 case EventEntry::Type::FOCUS:
2975 case EventEntry::Type::CONFIGURATION_CHANGED:
2976 case EventEntry::Type::DEVICE_RESET: {
2977 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2978 EventEntry::typeToString(downEventEntry->type));
2979 break;
2980 }
2981 }
2982
2983 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2984 target, InputTarget::FLAG_DISPATCH_AS_IS);
2985
2986 downEventEntry->release();
2987 }
2988
2989 startDispatchCycleLocked(currentTime, connection);
2990}
2991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002992MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002993 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 ALOG_ASSERT(pointerIds.value != 0);
2995
2996 uint32_t splitPointerIndexMap[MAX_POINTERS];
2997 PointerProperties splitPointerProperties[MAX_POINTERS];
2998 PointerCoords splitPointerCoords[MAX_POINTERS];
2999
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 uint32_t splitPointerCount = 0;
3002
3003 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 uint32_t pointerId = uint32_t(pointerProperties.id);
3008 if (pointerIds.hasBit(pointerId)) {
3009 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3010 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3011 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 splitPointerCount += 1;
3014 }
3015 }
3016
3017 if (splitPointerCount != pointerIds.count()) {
3018 // This is bad. We are missing some of the pointers that we expected to deliver.
3019 // Most likely this indicates that we received an ACTION_MOVE events that has
3020 // different pointer ids than we expected based on the previous ACTION_DOWN
3021 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3022 // in this way.
3023 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 "we expected there to be %d pointers. This probably means we received "
3025 "a broken sequence of pointer ids from the input device.",
3026 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003027 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 }
3029
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003030 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3033 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3035 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003036 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 uint32_t pointerId = uint32_t(pointerProperties.id);
3038 if (pointerIds.hasBit(pointerId)) {
3039 if (pointerIds.count() == 1) {
3040 // The first/last pointer went down/up.
3041 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 ? AMOTION_EVENT_ACTION_DOWN
3043 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 } else {
3045 // A secondary pointer went down/up.
3046 uint32_t splitPointerIndex = 0;
3047 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3048 splitPointerIndex += 1;
3049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 action = maskedAction |
3051 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053 } else {
3054 // An unrelated pointer changed.
3055 action = AMOTION_EVENT_ACTION_MOVE;
3056 }
3057 }
3058
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003059 int32_t newId = mIdGenerator.nextId();
3060 if (ATRACE_ENABLED()) {
3061 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3062 ") to MotionEvent(id=0x%" PRIx32 ").",
3063 originalMotionEntry.id, newId);
3064 ATRACE_NAME(message.c_str());
3065 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003066 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003067 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3068 originalMotionEntry.source, originalMotionEntry.displayId,
3069 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003070 originalMotionEntry.actionButton, originalMotionEntry.flags,
3071 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3072 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3073 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3074 originalMotionEntry.xCursorPosition,
3075 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003076 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003078 if (originalMotionEntry.injectionState) {
3079 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 splitMotionEntry->injectionState->refCount += 1;
3081 }
3082
3083 return splitMotionEntry;
3084}
3085
3086void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3087#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003088 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#endif
3090
3091 bool needWake;
3092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Prabir Pradhan42611e02018-11-27 14:04:02 -08003095 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003096 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 needWake = enqueueInboundEventLocked(newEntry);
3098 } // release lock
3099
3100 if (needWake) {
3101 mLooper->wake();
3102 }
3103}
3104
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003105/**
3106 * If one of the meta shortcuts is detected, process them here:
3107 * Meta + Backspace -> generate BACK
3108 * Meta + Enter -> generate HOME
3109 * This will potentially overwrite keyCode and metaState.
3110 */
3111void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003113 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3114 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3115 if (keyCode == AKEYCODE_DEL) {
3116 newKeyCode = AKEYCODE_BACK;
3117 } else if (keyCode == AKEYCODE_ENTER) {
3118 newKeyCode = AKEYCODE_HOME;
3119 }
3120 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003121 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003122 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003123 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003124 keyCode = newKeyCode;
3125 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3126 }
3127 } else if (action == AKEY_EVENT_ACTION_UP) {
3128 // In order to maintain a consistent stream of up and down events, check to see if the key
3129 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3130 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003131 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003132 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003133 auto replacementIt = mReplacedKeys.find(replacement);
3134 if (replacementIt != mReplacedKeys.end()) {
3135 keyCode = replacementIt->second;
3136 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003137 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3138 }
3139 }
3140}
3141
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3143#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3145 "policyFlags=0x%x, action=0x%x, "
3146 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3147 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3148 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3149 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#endif
3151 if (!validateKeyEvent(args->action)) {
3152 return;
3153 }
3154
3155 uint32_t policyFlags = args->policyFlags;
3156 int32_t flags = args->flags;
3157 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003158 // InputDispatcher tracks and generates key repeats on behalf of
3159 // whatever notifies it, so repeatCount should always be set to 0
3160 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3162 policyFlags |= POLICY_FLAG_VIRTUAL;
3163 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 if (policyFlags & POLICY_FLAG_FUNCTION) {
3166 metaState |= AMETA_FUNCTION_ON;
3167 }
3168
3169 policyFlags |= POLICY_FLAG_TRUSTED;
3170
Michael Wright78f24442014-08-06 15:55:28 -07003171 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003172 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003173
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003175 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003176 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3177 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
Michael Wright2b3c3302018-03-02 17:19:13 +00003179 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003181 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3182 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 bool needWake;
3187 { // acquire lock
3188 mLock.lock();
3189
3190 if (shouldSendKeyToInputFilterLocked(args)) {
3191 mLock.unlock();
3192
3193 policyFlags |= POLICY_FLAG_FILTERED;
3194 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3195 return; // event was consumed by the filter
3196 }
3197
3198 mLock.lock();
3199 }
3200
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003202 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 args->displayId, policyFlags, args->action, flags, keyCode,
3204 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 needWake = enqueueInboundEventLocked(newEntry);
3207 mLock.unlock();
3208 } // release lock
3209
3210 if (needWake) {
3211 mLooper->wake();
3212 }
3213}
3214
3215bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3216 return mInputFilterEnabled;
3217}
3218
3219void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3220#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003221 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3222 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003223 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3224 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003225 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003226 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3227 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3228 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3229 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 for (uint32_t i = 0; i < args->pointerCount; i++) {
3231 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 "x=%f, y=%f, pressure=%f, size=%f, "
3233 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3234 "orientation=%f",
3235 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3236 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3237 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3238 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3239 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3240 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3241 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3242 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3243 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3244 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
3246#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3248 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 return;
3250 }
3251
3252 uint32_t policyFlags = args->policyFlags;
3253 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003254
3255 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003256 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003257 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3258 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
3262 bool needWake;
3263 { // acquire lock
3264 mLock.lock();
3265
3266 if (shouldSendMotionToInputFilterLocked(args)) {
3267 mLock.unlock();
3268
3269 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003270 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003271 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3272 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003273 args->metaState, args->buttonState, args->classification, transform,
3274 args->xPrecision, args->yPrecision, args->xCursorPosition,
3275 args->yCursorPosition, args->downTime, args->eventTime,
3276 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
3278 policyFlags |= POLICY_FLAG_FILTERED;
3279 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3280 return; // event was consumed by the filter
3281 }
3282
3283 mLock.lock();
3284 }
3285
3286 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003287 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003288 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003289 args->displayId, policyFlags, args->action, args->actionButton,
3290 args->flags, args->metaState, args->buttonState,
3291 args->classification, args->edgeFlags, args->xPrecision,
3292 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3293 args->downTime, args->pointerCount, args->pointerProperties,
3294 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
3296 needWake = enqueueInboundEventLocked(newEntry);
3297 mLock.unlock();
3298 } // release lock
3299
3300 if (needWake) {
3301 mLooper->wake();
3302 }
3303}
3304
3305bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003306 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307}
3308
3309void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3310#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003311 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 "switchMask=0x%08x",
3313 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314#endif
3315
3316 uint32_t policyFlags = args->policyFlags;
3317 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319}
3320
3321void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3322#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3324 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#endif
3326
3327 bool needWake;
3328 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003329 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Prabir Pradhan42611e02018-11-27 14:04:02 -08003331 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003332 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 needWake = enqueueInboundEventLocked(newEntry);
3334 } // release lock
3335
3336 if (needWake) {
3337 mLooper->wake();
3338 }
3339}
3340
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3342 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003343 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344#if DEBUG_INBOUND_EVENT_DETAILS
3345 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003346 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3347 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003349 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
3351 policyFlags |= POLICY_FLAG_INJECTED;
3352 if (hasInjectionPermission(injectorPid, injectorUid)) {
3353 policyFlags |= POLICY_FLAG_TRUSTED;
3354 }
3355
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003356 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003359 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3360 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 if (!validateKeyEvent(action)) {
3362 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003365 int32_t flags = incomingKey.getFlags();
3366 int32_t keyCode = incomingKey.getKeyCode();
3367 int32_t metaState = incomingKey.getMetaState();
3368 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003370 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003371 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003372 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3373 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3374 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3377 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003378 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379
3380 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3381 android::base::Timer t;
3382 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3383 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3384 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3385 std::to_string(t.duration().count()).c_str());
3386 }
3387 }
3388
3389 mLock.lock();
3390 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003391 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3392 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003393 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3394 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003395 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 injectedEntries.push(injectedEntry);
3397 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003400 case AINPUT_EVENT_TYPE_MOTION: {
3401 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3402 int32_t action = motionEvent->getAction();
3403 size_t pointerCount = motionEvent->getPointerCount();
3404 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3405 int32_t actionButton = motionEvent->getActionButton();
3406 int32_t displayId = motionEvent->getDisplayId();
3407 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3408 return INPUT_EVENT_INJECTION_FAILED;
3409 }
3410
3411 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3412 nsecs_t eventTime = motionEvent->getEventTime();
3413 android::base::Timer t;
3414 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3415 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3416 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3417 std::to_string(t.duration().count()).c_str());
3418 }
3419 }
3420
3421 mLock.lock();
3422 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3423 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3424 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003425 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3426 motionEvent->getSource(), motionEvent->getDisplayId(),
3427 policyFlags, action, actionButton, motionEvent->getFlags(),
3428 motionEvent->getMetaState(), motionEvent->getButtonState(),
3429 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3430 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003431 motionEvent->getRawXCursorPosition(),
3432 motionEvent->getRawYCursorPosition(),
3433 motionEvent->getDownTime(), uint32_t(pointerCount),
3434 pointerProperties, samplePointerCoords,
3435 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 injectedEntries.push(injectedEntry);
3437 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3438 sampleEventTimes += 1;
3439 samplePointerCoords += pointerCount;
3440 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003441 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003442 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003443 motionEvent->getDisplayId(), policyFlags, action,
3444 actionButton, motionEvent->getFlags(),
3445 motionEvent->getMetaState(), motionEvent->getButtonState(),
3446 motionEvent->getClassification(),
3447 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3448 motionEvent->getYPrecision(),
3449 motionEvent->getRawXCursorPosition(),
3450 motionEvent->getRawYCursorPosition(),
3451 motionEvent->getDownTime(), uint32_t(pointerCount),
3452 pointerProperties, samplePointerCoords,
3453 motionEvent->getXOffset(), motionEvent->getYOffset());
3454 injectedEntries.push(nextInjectedEntry);
3455 }
3456 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003460 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
3463
3464 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3465 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3466 injectionState->injectionIsAsync = true;
3467 }
3468
3469 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003470 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
3472 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003473 while (!injectedEntries.empty()) {
3474 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3475 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 }
3477
3478 mLock.unlock();
3479
3480 if (needWake) {
3481 mLooper->wake();
3482 }
3483
3484 int32_t injectionResult;
3485 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003486 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487
3488 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3489 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3490 } else {
3491 for (;;) {
3492 injectionResult = injectionState->injectionResult;
3493 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3494 break;
3495 }
3496
3497 nsecs_t remainingTimeout = endTime - now();
3498 if (remainingTimeout <= 0) {
3499#if DEBUG_INJECTION
3500 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003501 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502#endif
3503 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3504 break;
3505 }
3506
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003507 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
3509
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3511 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 while (injectionState->pendingForegroundDispatches != 0) {
3513#if DEBUG_INJECTION
3514 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516#endif
3517 nsecs_t remainingTimeout = endTime - now();
3518 if (remainingTimeout <= 0) {
3519#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3521 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522#endif
3523 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3524 break;
3525 }
3526
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003527 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529 }
3530 }
3531
3532 injectionState->release();
3533 } // release lock
3534
3535#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003536 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003537 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538#endif
3539
3540 return injectionResult;
3541}
3542
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003543std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003544 std::array<uint8_t, 32> calculatedHmac;
3545 std::unique_ptr<VerifiedInputEvent> result;
3546 switch (event.getType()) {
3547 case AINPUT_EVENT_TYPE_KEY: {
3548 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3549 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3550 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003551 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003552 break;
3553 }
3554 case AINPUT_EVENT_TYPE_MOTION: {
3555 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3556 VerifiedMotionEvent verifiedMotionEvent =
3557 verifiedMotionEventFromMotionEvent(motionEvent);
3558 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003559 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003560 break;
3561 }
3562 default: {
3563 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3564 return nullptr;
3565 }
3566 }
3567 if (calculatedHmac == INVALID_HMAC) {
3568 return nullptr;
3569 }
3570 if (calculatedHmac != event.getHmac()) {
3571 return nullptr;
3572 }
3573 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003574}
3575
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003577 return injectorUid == 0 ||
3578 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579}
3580
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003581void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 InjectionState* injectionState = entry->injectionState;
3583 if (injectionState) {
3584#if DEBUG_INJECTION
3585 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003586 "injectorPid=%d, injectorUid=%d",
3587 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588#endif
3589
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 // Log the outcome since the injector did not wait for the injection result.
3592 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003593 case INPUT_EVENT_INJECTION_SUCCEEDED:
3594 ALOGV("Asynchronous input event injection succeeded.");
3595 break;
3596 case INPUT_EVENT_INJECTION_FAILED:
3597 ALOGW("Asynchronous input event injection failed.");
3598 break;
3599 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3600 ALOGW("Asynchronous input event injection permission denied.");
3601 break;
3602 case INPUT_EVENT_INJECTION_TIMED_OUT:
3603 ALOGW("Asynchronous input event injection timed out.");
3604 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606 }
3607
3608 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003609 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611}
3612
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003613void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 InjectionState* injectionState = entry->injectionState;
3615 if (injectionState) {
3616 injectionState->pendingForegroundDispatches += 1;
3617 }
3618}
3619
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003620void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 InjectionState* injectionState = entry->injectionState;
3622 if (injectionState) {
3623 injectionState->pendingForegroundDispatches -= 1;
3624
3625 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003626 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 }
3628 }
3629}
3630
Vishnu Nairad321cd2020-08-20 16:40:21 -07003631const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003632 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003633 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3634 auto it = mWindowHandlesByDisplay.find(displayId);
3635 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003636}
3637
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003639 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003640 if (windowHandleToken == nullptr) {
3641 return nullptr;
3642 }
3643
Arthur Hungb92218b2018-08-14 12:00:21 +08003644 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003645 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003646 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003647 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 return windowHandle;
3649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 }
3651 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003652 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653}
3654
Vishnu Nairad321cd2020-08-20 16:40:21 -07003655sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3656 int displayId) const {
3657 if (windowHandleToken == nullptr) {
3658 return nullptr;
3659 }
3660
3661 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3662 if (windowHandle->getToken() == windowHandleToken) {
3663 return windowHandle;
3664 }
3665 }
3666 return nullptr;
3667}
3668
3669sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3670 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3671 return getWindowHandleLocked(focusedToken, displayId);
3672}
3673
Mady Mellor017bcd12020-06-23 19:12:00 +00003674bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3675 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003676 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003677 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003678 if (handle->getId() == windowHandle->getId() &&
3679 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003680 if (windowHandle->getInfo()->displayId != it.first) {
3681 ALOGE("Found window %s in display %" PRId32
3682 ", but it should belong to display %" PRId32,
3683 windowHandle->getName().c_str(), it.first,
3684 windowHandle->getInfo()->displayId);
3685 }
3686 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689 }
3690 return false;
3691}
3692
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003693bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3694 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3695 const bool noInputChannel =
3696 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3697 if (connection != nullptr && noInputChannel) {
3698 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3699 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3700 return false;
3701 }
3702
3703 if (connection == nullptr) {
3704 if (!noInputChannel) {
3705 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3706 }
3707 return false;
3708 }
3709 if (!connection->responsive) {
3710 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3711 return false;
3712 }
3713 return true;
3714}
3715
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003716std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3717 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003718 size_t count = mInputChannelsByToken.count(token);
3719 if (count == 0) {
3720 return nullptr;
3721 }
3722 return mInputChannelsByToken.at(token);
3723}
3724
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003725void InputDispatcher::updateWindowHandlesForDisplayLocked(
3726 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3727 if (inputWindowHandles.empty()) {
3728 // Remove all handles on a display if there are no windows left.
3729 mWindowHandlesByDisplay.erase(displayId);
3730 return;
3731 }
3732
3733 // Since we compare the pointer of input window handles across window updates, we need
3734 // to make sure the handle object for the same window stays unchanged across updates.
3735 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003736 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003737 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003738 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003739 }
3740
3741 std::vector<sp<InputWindowHandle>> newHandles;
3742 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3743 if (!handle->updateInfo()) {
3744 // handle no longer valid
3745 continue;
3746 }
3747
3748 const InputWindowInfo* info = handle->getInfo();
3749 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3750 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3751 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003752 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3753 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3754 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003755 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003756 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003757 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003758 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003759 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003760 }
3761
3762 if (info->displayId != displayId) {
3763 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3764 handle->getName().c_str(), displayId, info->displayId);
3765 continue;
3766 }
3767
Robert Carredd13602020-04-13 17:24:34 -07003768 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3769 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003770 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003771 oldHandle->updateFrom(handle);
3772 newHandles.push_back(oldHandle);
3773 } else {
3774 newHandles.push_back(handle);
3775 }
3776 }
3777
3778 // Insert or replace
3779 mWindowHandlesByDisplay[displayId] = newHandles;
3780}
3781
Arthur Hung72d8dc32020-03-28 00:48:39 +00003782void InputDispatcher::setInputWindows(
3783 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3784 { // acquire lock
3785 std::scoped_lock _l(mLock);
3786 for (auto const& i : handlesPerDisplay) {
3787 setInputWindowsLocked(i.second, i.first);
3788 }
3789 }
3790 // Wake up poll loop since it may need to make new input dispatching choices.
3791 mLooper->wake();
3792}
3793
Arthur Hungb92218b2018-08-14 12:00:21 +08003794/**
3795 * Called from InputManagerService, update window handle list by displayId that can receive input.
3796 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3797 * If set an empty list, remove all handles from the specific display.
3798 * For focused handle, check if need to change and send a cancel event to previous one.
3799 * For removed handle, check if need to send a cancel event if already in touch.
3800 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003801void InputDispatcher::setInputWindowsLocked(
3802 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003803 if (DEBUG_FOCUS) {
3804 std::string windowList;
3805 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3806 windowList += iwh->getName() + " ";
3807 }
3808 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003811 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3812 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3813 const bool noInputWindow =
3814 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3815 if (noInputWindow && window->getToken() != nullptr) {
3816 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3817 window->getName().c_str());
3818 window->releaseChannel();
3819 }
3820 }
3821
Arthur Hung72d8dc32020-03-28 00:48:39 +00003822 // Copy old handles for release if they are no longer present.
3823 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824
Arthur Hung72d8dc32020-03-28 00:48:39 +00003825 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003826
Vishnu Nair958da932020-08-21 17:12:37 -07003827 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3828 if (mLastHoverWindowHandle &&
3829 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3830 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003831 mLastHoverWindowHandle = nullptr;
3832 }
3833
Vishnu Nair958da932020-08-21 17:12:37 -07003834 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3835 if (focusedToken) {
3836 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3837 if (result != FocusResult::OK) {
3838 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3839 }
3840 }
3841
3842 std::optional<FocusRequest> focusRequest =
3843 getOptionalValueByKey(mPendingFocusRequests, displayId);
3844 if (focusRequest) {
3845 // If the window from the pending request is now visible, provide it focus.
3846 FocusResult result = handleFocusRequestLocked(*focusRequest);
3847 if (result != FocusResult::NOT_VISIBLE) {
3848 // Drop the request if we were able to change the focus or we cannot change
3849 // it for another reason.
3850 mPendingFocusRequests.erase(displayId);
3851 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003854 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3855 mTouchStatesByDisplay.find(displayId);
3856 if (stateIt != mTouchStatesByDisplay.end()) {
3857 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003858 for (size_t i = 0; i < state.windows.size();) {
3859 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003860 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003861 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003862 ALOGD("Touched window was removed: %s in display %" PRId32,
3863 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003864 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003865 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003866 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3867 if (touchedInputChannel != nullptr) {
3868 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3869 "touched window was removed");
3870 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003872 state.windows.erase(state.windows.begin() + i);
3873 } else {
3874 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 }
3876 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003877 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003878
Arthur Hung72d8dc32020-03-28 00:48:39 +00003879 // Release information for windows that are no longer present.
3880 // This ensures that unused input channels are released promptly.
3881 // Otherwise, they might stick around until the window handle is destroyed
3882 // which might not happen until the next GC.
3883 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003884 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003885 if (DEBUG_FOCUS) {
3886 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003887 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003888 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003889 }
chaviw291d88a2019-02-14 10:33:58 -08003890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891}
3892
3893void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003894 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003895 if (DEBUG_FOCUS) {
3896 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3897 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3898 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
Chris Yea209fde2020-07-22 13:54:51 -07003902 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003903 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003904
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003905 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
3906 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003907 }
3908
Chris Yea209fde2020-07-22 13:54:51 -07003909 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003910 if (inputApplicationHandle != nullptr) {
3911 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3912 } else {
3913 mFocusedApplicationHandlesByDisplay.erase(displayId);
3914 }
3915
3916 // No matter what the old focused application was, stop waiting on it because it is
3917 // no longer focused.
3918 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 } // release lock
3920
3921 // Wake up poll loop since it may need to make new input dispatching choices.
3922 mLooper->wake();
3923}
3924
Tiger Huang721e26f2018-07-24 22:26:19 +08003925/**
3926 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3927 * the display not specified.
3928 *
3929 * We track any unreleased events for each window. If a window loses the ability to receive the
3930 * released event, we will send a cancel event to it. So when the focused display is changed, we
3931 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3932 * display. The display-specified events won't be affected.
3933 */
3934void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003935 if (DEBUG_FOCUS) {
3936 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3937 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003938 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003939 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003940
3941 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003942 sp<IBinder> oldFocusedWindowToken =
3943 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3944 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003945 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003946 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003947 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003948 CancelationOptions
3949 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3950 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003951 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003952 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3953 }
3954 }
3955 mFocusedDisplayId = displayId;
3956
Chris Ye3c2d6f52020-08-09 10:39:48 -07003957 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003958 sp<IBinder> newFocusedWindowToken =
3959 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3960 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003961
Vishnu Nairad321cd2020-08-20 16:40:21 -07003962 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003963 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003964 if (!mFocusedWindowTokenByDisplay.empty()) {
3965 ALOGE("But another display has a focused window\n%s",
3966 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003967 }
3968 }
3969 }
3970
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003971 if (DEBUG_FOCUS) {
3972 logDispatchStateLocked();
3973 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003974 } // release lock
3975
3976 // Wake up poll loop since it may need to make new input dispatching choices.
3977 mLooper->wake();
3978}
3979
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003981 if (DEBUG_FOCUS) {
3982 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984
3985 bool changed;
3986 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
3989 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3990 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003991 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993
3994 if (mDispatchEnabled && !enabled) {
3995 resetAndDropEverythingLocked("dispatcher is being disabled");
3996 }
3997
3998 mDispatchEnabled = enabled;
3999 mDispatchFrozen = frozen;
4000 changed = true;
4001 } else {
4002 changed = false;
4003 }
4004
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004005 if (DEBUG_FOCUS) {
4006 logDispatchStateLocked();
4007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 } // release lock
4009
4010 if (changed) {
4011 // Wake up poll loop since it may need to make new input dispatching choices.
4012 mLooper->wake();
4013 }
4014}
4015
4016void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004017 if (DEBUG_FOCUS) {
4018 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020
4021 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
4024 if (mInputFilterEnabled == enabled) {
4025 return;
4026 }
4027
4028 mInputFilterEnabled = enabled;
4029 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4030 } // release lock
4031
4032 // Wake up poll loop since there might be work to do to drop everything.
4033 mLooper->wake();
4034}
4035
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004036void InputDispatcher::setInTouchMode(bool inTouchMode) {
4037 std::scoped_lock lock(mLock);
4038 mInTouchMode = inTouchMode;
4039}
4040
chaviwfbe5d9c2018-12-26 12:23:37 -08004041bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4042 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004043 if (DEBUG_FOCUS) {
4044 ALOGD("Trivial transfer to same window.");
4045 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004046 return true;
4047 }
4048
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004050 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
chaviwfbe5d9c2018-12-26 12:23:37 -08004052 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4053 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004054 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004055 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 return false;
4057 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004058 if (DEBUG_FOCUS) {
4059 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4060 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004063 if (DEBUG_FOCUS) {
4064 ALOGD("Cannot transfer focus because windows are on different displays.");
4065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 return false;
4067 }
4068
4069 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004070 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4071 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004072 for (size_t i = 0; i < state.windows.size(); i++) {
4073 const TouchedWindow& touchedWindow = state.windows[i];
4074 if (touchedWindow.windowHandle == fromWindowHandle) {
4075 int32_t oldTargetFlags = touchedWindow.targetFlags;
4076 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004078 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 int32_t newTargetFlags = oldTargetFlags &
4081 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4082 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004083 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
Jeff Brownf086ddb2014-02-11 14:28:48 -08004085 found = true;
4086 goto Found;
4087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 }
4089 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004093 if (DEBUG_FOCUS) {
4094 ALOGD("Focus transfer failed because from window did not have focus.");
4095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 return false;
4097 }
4098
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004099 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4100 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004101 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004102 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 CancelationOptions
4104 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4105 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004107 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 }
4109
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004110 if (DEBUG_FOCUS) {
4111 logDispatchStateLocked();
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 } // release lock
4114
4115 // Wake up poll loop since it may need to make new input dispatching choices.
4116 mLooper->wake();
4117 return true;
4118}
4119
4120void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004121 if (DEBUG_FOCUS) {
4122 ALOGD("Resetting and dropping all events (%s).", reason);
4123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
4125 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4126 synthesizeCancelationEventsForAllConnectionsLocked(options);
4127
4128 resetKeyRepeatLocked();
4129 releasePendingEventLocked();
4130 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004131 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004133 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004134 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004136 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137}
4138
4139void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 dumpDispatchStateLocked(dump);
4142
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004143 std::istringstream stream(dump);
4144 std::string line;
4145
4146 while (std::getline(stream, line, '\n')) {
4147 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 }
4149}
4150
Vishnu Nairad321cd2020-08-20 16:40:21 -07004151std::string InputDispatcher::dumpFocusedWindowsLocked() {
4152 if (mFocusedWindowTokenByDisplay.empty()) {
4153 return INDENT "FocusedWindows: <none>\n";
4154 }
4155
4156 std::string dump;
4157 dump += INDENT "FocusedWindows:\n";
4158 for (auto& it : mFocusedWindowTokenByDisplay) {
4159 const int32_t displayId = it.first;
4160 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4161 if (windowHandle) {
4162 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4163 windowHandle->getName().c_str());
4164 } else {
4165 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4166 " has focused token without a window'\n",
4167 displayId);
4168 }
4169 }
4170 return dump;
4171}
4172
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004174 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4175 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4176 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004177 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Tiger Huang721e26f2018-07-24 22:26:19 +08004179 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4180 dump += StringPrintf(INDENT "FocusedApplications:\n");
4181 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4182 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004183 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004184 const std::chrono::duration timeout =
4185 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004187 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004188 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004191 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004193
Vishnu Nairad321cd2020-08-20 16:40:21 -07004194 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004196 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004198 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4199 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 state.displayId, toString(state.down), toString(state.split),
4202 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004203 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004205 for (size_t i = 0; i < state.windows.size(); i++) {
4206 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 dump += StringPrintf(INDENT4
4208 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4209 i, touchedWindow.windowHandle->getName().c_str(),
4210 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004211 }
4212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004214 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004215 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004216 dump += INDENT3 "Portal windows:\n";
4217 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004218 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004219 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4220 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004221 }
4222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227
Arthur Hungb92218b2018-08-14 12:00:21 +08004228 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004230 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004231 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004232 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004233 dump += INDENT2 "Windows:\n";
4234 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004235 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004236 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
Arthur Hungb92218b2018-08-14 12:00:21 +08004238 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004239 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4240 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004241 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004243 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004244 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 i, windowInfo->name.c_str(), windowInfo->displayId,
4246 windowInfo->portalToDisplayId,
4247 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004248 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 toString(windowInfo->hasWallpaper),
4250 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004251 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004252 static_cast<int32_t>(windowInfo->type),
4253 windowInfo->frameLeft, windowInfo->frameTop,
4254 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004255 windowInfo->globalScaleFactor,
4256 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004257 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004258 dump += StringPrintf(", inputFeatures=%s",
4259 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004260 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4261 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004263 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004264 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004265 }
4266 } else {
4267 dump += INDENT2 "Windows: <none>\n";
4268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004271 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 }
4273
Michael Wright3dd60e22019-03-27 22:06:44 +00004274 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004276 const std::vector<Monitor>& monitors = it.second;
4277 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4278 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 }
4280 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004281 const std::vector<Monitor>& monitors = it.second;
4282 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4283 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004286 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 }
4288
4289 nsecs_t currentTime = now();
4290
4291 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004292 if (!mRecentQueue.empty()) {
4293 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4294 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004297 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
4299 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004300 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
4302
4303 // Dump event currently being dispatched.
4304 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004305 dump += INDENT "PendingEvent:\n";
4306 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004308 dump += StringPrintf(", age=%" PRId64 "ms\n",
4309 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004311 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
4313
4314 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004315 if (!mInboundQueue.empty()) {
4316 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4317 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004318 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004320 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004323 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004326 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004327 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004328 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4329 const KeyReplacement& replacement = pair.first;
4330 int32_t newKeyCode = pair.second;
4331 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004332 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004333 }
4334 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004335 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004336 }
4337
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004338 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004339 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004340 for (const auto& pair : mConnectionsByFd) {
4341 const sp<Connection>& connection = pair.second;
4342 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004343 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004344 pair.first, connection->getInputChannelName().c_str(),
4345 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004346 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004348 if (!connection->outboundQueue.empty()) {
4349 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4350 connection->outboundQueue.size());
4351 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 dump.append(INDENT4);
4353 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004354 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4355 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 }
4359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004360 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
4362
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004363 if (!connection->waitQueue.empty()) {
4364 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4365 connection->waitQueue.size());
4366 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004370 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004372 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004373 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 }
4375 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004376 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 }
4378 }
4379 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004380 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 }
4382
4383 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4385 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004387 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004391 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4392 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4393 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394}
4395
Michael Wright3dd60e22019-03-27 22:06:44 +00004396void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4397 const size_t numMonitors = monitors.size();
4398 for (size_t i = 0; i < numMonitors; i++) {
4399 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004400 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004401 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4402 dump += "\n";
4403 }
4404}
4405
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004406status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004408 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409#endif
4410
4411 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004412 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004413 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004414 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 return BAD_VALUE;
4418 }
4419
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004420 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421
4422 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004423 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004424 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4427 } // release lock
4428
4429 // Wake the looper because some connections have changed.
4430 mLooper->wake();
4431 return OK;
4432}
4433
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004434status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004435 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004436 { // acquire lock
4437 std::scoped_lock _l(mLock);
4438
4439 if (displayId < 0) {
4440 ALOGW("Attempted to register input monitor without a specified display.");
4441 return BAD_VALUE;
4442 }
4443
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004444 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004445 ALOGW("Attempted to register input monitor without an identifying token.");
4446 return BAD_VALUE;
4447 }
4448
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004449 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004450
4451 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004452 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004453 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004454
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 auto& monitorsByDisplay =
4456 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004457 monitorsByDisplay[displayId].emplace_back(inputChannel);
4458
4459 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004460 }
4461 // Wake the looper because some connections have changed.
4462 mLooper->wake();
4463 return OK;
4464}
4465
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004466status_t InputDispatcher::unregisterInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004468 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004470 status_t status = unregisterInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 if (status) {
4472 return status;
4473 }
4474 } // release lock
4475
4476 // Wake the poll loop because removing the connection may have changed the current
4477 // synchronization state.
4478 mLooper->wake();
4479 return OK;
4480}
4481
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004482status_t InputDispatcher::unregisterInputChannelLocked(const sp<IBinder>& connectionToken,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004483 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004484 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004485 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004486 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 return BAD_VALUE;
4488 }
4489
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004490 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004491 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004492
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004494 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004497 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498
4499 nsecs_t currentTime = now();
4500 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4501
4502 connection->status = Connection::STATUS_ZOMBIE;
4503 return OK;
4504}
4505
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004506void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4507 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4508 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004509}
4510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004512 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004513 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004514 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004515 std::vector<Monitor>& monitors = it->second;
4516 const size_t numMonitors = monitors.size();
4517 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004518 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519 monitors.erase(monitors.begin() + i);
4520 break;
4521 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004522 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004523 if (monitors.empty()) {
4524 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004525 } else {
4526 ++it;
4527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 }
4529}
4530
Michael Wright3dd60e22019-03-27 22:06:44 +00004531status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4532 { // acquire lock
4533 std::scoped_lock _l(mLock);
4534 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4535
4536 if (!foundDisplayId) {
4537 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4538 return BAD_VALUE;
4539 }
4540 int32_t displayId = foundDisplayId.value();
4541
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004542 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4543 mTouchStatesByDisplay.find(displayId);
4544 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004545 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4546 return BAD_VALUE;
4547 }
4548
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004549 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004550 std::optional<int32_t> foundDeviceId;
4551 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004552 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004553 foundDeviceId = state.deviceId;
4554 }
4555 }
4556 if (!foundDeviceId || !state.down) {
4557 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004558 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004559 return BAD_VALUE;
4560 }
4561 int32_t deviceId = foundDeviceId.value();
4562
4563 // Send cancel events to all the input channels we're stealing from.
4564 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004565 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004566 options.deviceId = deviceId;
4567 options.displayId = displayId;
4568 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004569 std::shared_ptr<InputChannel> channel =
4570 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004571 if (channel != nullptr) {
4572 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4573 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004574 }
4575 // Then clear the current touch state so we stop dispatching to them as well.
4576 state.filterNonMonitors();
4577 }
4578 return OK;
4579}
4580
Michael Wright3dd60e22019-03-27 22:06:44 +00004581std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4582 const sp<IBinder>& token) {
4583 for (const auto& it : mGestureMonitorsByDisplay) {
4584 const std::vector<Monitor>& monitors = it.second;
4585 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004586 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004587 return it.first;
4588 }
4589 }
4590 }
4591 return std::nullopt;
4592}
4593
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004594sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004595 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004596 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004597 }
4598
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004599 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004600 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004601 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004602 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604 }
Robert Carr4e670e52018-08-15 13:26:12 -07004605
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004606 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607}
4608
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004610 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004611 removeByValue(mConnectionsByFd, connection);
4612}
4613
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4615 const sp<Connection>& connection, uint32_t seq,
4616 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004617 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4618 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 commandEntry->connection = connection;
4620 commandEntry->eventTime = currentTime;
4621 commandEntry->seq = seq;
4622 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004623 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624}
4625
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004626void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4627 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004631 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4632 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004634 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635}
4636
Vishnu Nairad321cd2020-08-20 16:40:21 -07004637void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4638 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004639 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4640 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004641 commandEntry->oldToken = oldToken;
4642 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004643 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004644}
4645
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004646void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4647 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4648 // is already healthy again. Don't raise ANR in this situation
4649 if (connection->waitQueue.empty()) {
4650 ALOGI("Not raising ANR because the connection %s has recovered",
4651 connection->inputChannel->getName().c_str());
4652 return;
4653 }
4654 /**
4655 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4656 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4657 * has changed. This could cause newer entries to time out before the already dispatched
4658 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4659 * processes the events linearly. So providing information about the oldest entry seems to be
4660 * most useful.
4661 */
4662 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4663 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4664 std::string reason =
4665 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4666 connection->inputChannel->getName().c_str(),
4667 ns2ms(currentWait),
4668 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004670 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4671 reason);
4672
4673 std::unique_ptr<CommandEntry> commandEntry =
4674 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4675 commandEntry->inputApplicationHandle = nullptr;
4676 commandEntry->inputChannel = connection->inputChannel;
4677 commandEntry->reason = std::move(reason);
4678 postCommandLocked(std::move(commandEntry));
4679}
4680
Chris Yea209fde2020-07-22 13:54:51 -07004681void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4683 application->getName().c_str());
4684
4685 updateLastAnrStateLocked(application, reason);
4686
4687 std::unique_ptr<CommandEntry> commandEntry =
4688 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4689 commandEntry->inputApplicationHandle = application;
4690 commandEntry->inputChannel = nullptr;
4691 commandEntry->reason = std::move(reason);
4692 postCommandLocked(std::move(commandEntry));
4693}
4694
4695void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4696 const std::string& reason) {
4697 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4698 updateLastAnrStateLocked(windowLabel, reason);
4699}
4700
Chris Yea209fde2020-07-22 13:54:51 -07004701void InputDispatcher::updateLastAnrStateLocked(
4702 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4704 updateLastAnrStateLocked(windowLabel, reason);
4705}
4706
4707void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4708 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004710 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 struct tm tm;
4712 localtime_r(&t, &tm);
4713 char timestr[64];
4714 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004715 mLastAnrState.clear();
4716 mLastAnrState += INDENT "ANR:\n";
4717 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4719 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004720 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721}
4722
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 mLock.unlock();
4725
4726 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4727
4728 mLock.lock();
4729}
4730
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004731void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 sp<Connection> connection = commandEntry->connection;
4733
4734 if (connection->status != Connection::STATUS_ZOMBIE) {
4735 mLock.unlock();
4736
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004737 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
4739 mLock.lock();
4740 }
4741}
4742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004744 sp<IBinder> oldToken = commandEntry->oldToken;
4745 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004746 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004747 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004748 mLock.lock();
4749}
4750
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004751void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004752 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004753 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 mLock.unlock();
4755
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004756 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004757 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
4759 mLock.lock();
4760
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004761 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004762 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4763 } else {
4764 // stop waking up for events in this connection, it is already not responding
4765 sp<Connection> connection = getConnectionLocked(token);
4766 if (connection == nullptr) {
4767 return;
4768 }
4769 cancelEventsForAnrLocked(connection);
4770 }
4771}
4772
Chris Yea209fde2020-07-22 13:54:51 -07004773void InputDispatcher::extendAnrTimeoutsLocked(
4774 const std::shared_ptr<InputApplicationHandle>& application,
4775 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 sp<Connection> connection = getConnectionLocked(connectionToken);
4777 if (connection == nullptr) {
4778 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4779 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004780 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 mAwaitedFocusedApplication = application;
4782 } else {
4783 // It's also possible that the connection already disappeared. No action necessary.
4784 }
4785 return;
4786 }
4787
4788 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004789 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790
4791 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004792 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 for (DispatchEntry* entry : connection->waitQueue) {
4794 if (newTimeout >= entry->timeoutTime) {
4795 // Already removed old entries when connection was marked unresponsive
4796 entry->timeoutTime = newTimeout;
4797 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4798 }
4799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800}
4801
4802void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4803 CommandEntry* commandEntry) {
4804 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004805 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806
4807 mLock.unlock();
4808
Michael Wright2b3c3302018-03-02 17:19:13 +00004809 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004811 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 : nullptr;
4813 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004814 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4815 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
4819 mLock.lock();
4820
4821 if (delay < 0) {
4822 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4823 } else if (!delay) {
4824 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4825 } else {
4826 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4827 entry->interceptKeyWakeupTime = now() + delay;
4828 }
4829 entry->release();
4830}
4831
chaviwfd6d3512019-03-25 13:23:49 -07004832void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4833 mLock.unlock();
4834 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4835 mLock.lock();
4836}
4837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838/**
4839 * Connection is responsive if it has no events in the waitQueue that are older than the
4840 * current time.
4841 */
4842static bool isConnectionResponsive(const Connection& connection) {
4843 const nsecs_t currentTime = now();
4844 for (const DispatchEntry* entry : connection.waitQueue) {
4845 if (entry->timeoutTime < currentTime) {
4846 return false;
4847 }
4848 }
4849 return true;
4850}
4851
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004852void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004854 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004856 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
4858 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004859 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004860 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004861 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004863 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004864 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004865 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004866 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4867 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004869 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004870
4871 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004872 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004873 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4874 restartEvent =
4875 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004876 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004877 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4878 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4879 handled);
4880 } else {
4881 restartEvent = false;
4882 }
4883
4884 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004885 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004886 // contents of the wait queue to have been drained, so we need to double-check
4887 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004888 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4889 if (dispatchEntryIt != connection->waitQueue.end()) {
4890 dispatchEntry = *dispatchEntryIt;
4891 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004892 mAnrTracker.erase(dispatchEntry->timeoutTime,
4893 connection->inputChannel->getConnectionToken());
4894 if (!connection->responsive) {
4895 connection->responsive = isConnectionResponsive(*connection);
4896 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004897 traceWaitQueueLength(connection);
4898 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004899 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004900 traceOutboundQueueLength(connection);
4901 } else {
4902 releaseDispatchEntry(dispatchEntry);
4903 }
4904 }
4905
4906 // Start the next dispatch cycle for this connection.
4907 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908}
4909
4910bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004911 DispatchEntry* dispatchEntry,
4912 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004913 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004914 if (!handled) {
4915 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004916 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004917 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004918 return false;
4919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004921 // Get the fallback key state.
4922 // Clear it out after dispatching the UP.
4923 int32_t originalKeyCode = keyEntry->keyCode;
4924 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4925 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4926 connection->inputState.removeFallbackKey(originalKeyCode);
4927 }
4928
4929 if (handled || !dispatchEntry->hasForegroundTarget()) {
4930 // If the application handles the original key for which we previously
4931 // generated a fallback or if the window is not a foreground window,
4932 // then cancel the associated fallback key, if any.
4933 if (fallbackKeyCode != -1) {
4934 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004936 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004937 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4938 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4939 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004941 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004942 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
4944 mLock.unlock();
4945
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004946 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004947 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948
4949 mLock.lock();
4950
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004951 // Cancel the fallback key.
4952 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 "application handled the original non-fallback key "
4955 "or is no longer a foreground target, "
4956 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 options.keyCode = fallbackKeyCode;
4958 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004960 connection->inputState.removeFallbackKey(originalKeyCode);
4961 }
4962 } else {
4963 // If the application did not handle a non-fallback key, first check
4964 // that we are in a good state to perform unhandled key event processing
4965 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004966 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004967 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004970 "since this is not an initial down. "
4971 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4972 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004974 return false;
4975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004977 // Dispatch the unhandled key to the policy.
4978#if DEBUG_OUTBOUND_EVENT_DETAILS
4979 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4981 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004983 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004984
4985 mLock.unlock();
4986
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004987 bool fallback =
4988 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4989 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004990
4991 mLock.lock();
4992
4993 if (connection->status != Connection::STATUS_NORMAL) {
4994 connection->inputState.removeFallbackKey(originalKeyCode);
4995 return false;
4996 }
4997
4998 // Latch the fallback keycode for this key on an initial down.
4999 // The fallback keycode cannot change at any other point in the lifecycle.
5000 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005002 fallbackKeyCode = event.getKeyCode();
5003 } else {
5004 fallbackKeyCode = AKEYCODE_UNKNOWN;
5005 }
5006 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5007 }
5008
5009 ALOG_ASSERT(fallbackKeyCode != -1);
5010
5011 // Cancel the fallback key if the policy decides not to send it anymore.
5012 // We will continue to dispatch the key to the policy but we will no
5013 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005014 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5015 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005016#if DEBUG_OUTBOUND_EVENT_DETAILS
5017 if (fallback) {
5018 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 "as a fallback for %d, but on the DOWN it had requested "
5020 "to send %d instead. Fallback canceled.",
5021 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005022 } else {
5023 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 "but on the DOWN it had requested to send %d. "
5025 "Fallback canceled.",
5026 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005027 }
5028#endif
5029
5030 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5031 "canceling fallback, policy no longer desires it");
5032 options.keyCode = fallbackKeyCode;
5033 synthesizeCancelationEventsForConnectionLocked(connection, options);
5034
5035 fallback = false;
5036 fallbackKeyCode = AKEYCODE_UNKNOWN;
5037 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005039 }
5040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041
5042#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005043 {
5044 std::string msg;
5045 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5046 connection->inputState.getFallbackKeys();
5047 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005048 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005050 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005051 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005052 }
5053#endif
5054
5055 if (fallback) {
5056 // Restart the dispatch cycle using the fallback key.
5057 keyEntry->eventTime = event.getEventTime();
5058 keyEntry->deviceId = event.getDeviceId();
5059 keyEntry->source = event.getSource();
5060 keyEntry->displayId = event.getDisplayId();
5061 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5062 keyEntry->keyCode = fallbackKeyCode;
5063 keyEntry->scanCode = event.getScanCode();
5064 keyEntry->metaState = event.getMetaState();
5065 keyEntry->repeatCount = event.getRepeatCount();
5066 keyEntry->downTime = event.getDownTime();
5067 keyEntry->syntheticRepeat = false;
5068
5069#if DEBUG_OUTBOUND_EVENT_DETAILS
5070 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005071 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5072 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005073#endif
5074 return true; // restart the event
5075 } else {
5076#if DEBUG_OUTBOUND_EVENT_DETAILS
5077 ALOGD("Unhandled key event: No fallback key.");
5078#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005079
5080 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005081 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 }
5083 }
5084 return false;
5085}
5086
5087bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005088 DispatchEntry* dispatchEntry,
5089 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 return false;
5091}
5092
5093void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5094 mLock.unlock();
5095
5096 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5097
5098 mLock.lock();
5099}
5100
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005101KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5102 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005103 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005104 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5105 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005106 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107}
5108
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005109void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5110 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 // TODO Write some statistics about how long we spend waiting.
5112}
5113
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005114/**
5115 * Report the touch event latency to the statsd server.
5116 * Input events are reported for statistics if:
5117 * - This is a touchscreen event
5118 * - InputFilter is not enabled
5119 * - Event is not injected or synthesized
5120 *
5121 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5122 * from getting aggregated with the "old" data.
5123 */
5124void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5125 REQUIRES(mLock) {
5126 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5127 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5128 if (!reportForStatistics) {
5129 return;
5130 }
5131
5132 if (mTouchStatistics.shouldReport()) {
5133 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5134 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5135 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5136 mTouchStatistics.reset();
5137 }
5138 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5139 mTouchStatistics.addValue(latencyMicros);
5140}
5141
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142void InputDispatcher::traceInboundQueueLengthLocked() {
5143 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005144 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146}
5147
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005148void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 if (ATRACE_ENABLED()) {
5150 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005151 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005152 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154}
5155
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005156void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 if (ATRACE_ENABLED()) {
5158 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005159 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005160 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 }
5162}
5163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005164void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005165 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005167 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 dumpDispatchStateLocked(dump);
5169
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005170 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005171 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005172 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174}
5175
5176void InputDispatcher::monitor() {
5177 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005178 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005180 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005183/**
5184 * Wake up the dispatcher and wait until it processes all events and commands.
5185 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5186 * this method can be safely called from any thread, as long as you've ensured that
5187 * the work you are interested in completing has already been queued.
5188 */
5189bool InputDispatcher::waitForIdle() {
5190 /**
5191 * Timeout should represent the longest possible time that a device might spend processing
5192 * events and commands.
5193 */
5194 constexpr std::chrono::duration TIMEOUT = 100ms;
5195 std::unique_lock lock(mLock);
5196 mLooper->wake();
5197 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5198 return result == std::cv_status::no_timeout;
5199}
5200
Vishnu Naire798b472020-07-23 13:52:21 -07005201/**
5202 * Sets focus to the window identified by the token. This must be called
5203 * after updating any input window handles.
5204 *
5205 * Params:
5206 * request.token - input channel token used to identify the window that should gain focus.
5207 * request.focusedToken - the token that the caller expects currently to be focused. If the
5208 * specified token does not match the currently focused window, this request will be dropped.
5209 * If the specified focused token matches the currently focused window, the call will succeed.
5210 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5211 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5212 * when requesting the focus change. This determines which request gets
5213 * precedence if there is a focus change request from another source such as pointer down.
5214 */
Vishnu Nair958da932020-08-21 17:12:37 -07005215void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5216 { // acquire lock
5217 std::scoped_lock _l(mLock);
5218
5219 const int32_t displayId = request.displayId;
5220 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5221 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5222 ALOGD_IF(DEBUG_FOCUS,
5223 "setFocusedWindow on display %" PRId32
5224 " ignored, reason: focusedToken is not focused",
5225 displayId);
5226 return;
5227 }
5228
5229 mPendingFocusRequests.erase(displayId);
5230 FocusResult result = handleFocusRequestLocked(request);
5231 if (result == FocusResult::NOT_VISIBLE) {
5232 // The requested window is not currently visible. Wait for the window to become visible
5233 // and then provide it focus. This is to handle situations where a user action triggers
5234 // a new window to appear. We want to be able to queue any key events after the user
5235 // action and deliver it to the newly focused window. In order for this to happen, we
5236 // take focus from the currently focused window so key events can be queued.
5237 ALOGD_IF(DEBUG_FOCUS,
5238 "setFocusedWindow on display %" PRId32
5239 " pending, reason: window is not visible",
5240 displayId);
5241 mPendingFocusRequests[displayId] = request;
5242 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5243 "setFocusedWindow_AwaitingWindowVisibility");
5244 } else if (result != FocusResult::OK) {
5245 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5246 typeToString(result));
5247 }
5248 } // release lock
5249 // Wake up poll loop since it may need to make new input dispatching choices.
5250 mLooper->wake();
5251}
5252
5253InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5254 const FocusRequest& request) {
5255 const int32_t displayId = request.displayId;
5256 const sp<IBinder> newFocusedToken = request.token;
5257 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5258
5259 if (oldFocusedToken == request.token) {
5260 ALOGD_IF(DEBUG_FOCUS,
5261 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5262 displayId);
5263 return FocusResult::OK;
5264 }
5265
5266 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5267 if (result != FocusResult::OK) {
5268 return result;
5269 }
5270
5271 std::string_view reason =
5272 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5273 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5274 return FocusResult::OK;
5275}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005276
Vishnu Nairad321cd2020-08-20 16:40:21 -07005277void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5278 const sp<IBinder>& newFocusedToken, int32_t displayId,
5279 std::string_view reason) {
5280 if (oldFocusedToken) {
5281 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005282 if (focusedInputChannel) {
5283 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5284 "focus left window");
5285 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005286 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005287 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005288 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005289 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005290 if (newFocusedToken) {
5291 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5292 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005293 }
5294
5295 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005296 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005297 }
5298}
Vishnu Nair958da932020-08-21 17:12:37 -07005299
5300/**
5301 * Checks if the window token can be focused on a display. The token can be focused if there is
5302 * at least one window handle that is visible with the same token and all window handles with the
5303 * same token are focusable.
5304 *
5305 * In the case of mirroring, two windows may share the same window token and their visibility
5306 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5307 * we expect the focusability of the windows to match since its hard to reason why one window can
5308 * receive focus events and the other cannot when both are backed by the same input channel.
5309 */
5310InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5311 int32_t displayId) const {
5312 bool allWindowsAreFocusable = true;
5313 bool visibleWindowFound = false;
5314 bool windowFound = false;
5315 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5316 if (window->getToken() != token) {
5317 continue;
5318 }
5319 windowFound = true;
5320 if (window->getInfo()->visible) {
5321 // Check if at least a single window is visible.
5322 visibleWindowFound = true;
5323 }
5324 if (!window->getInfo()->focusable) {
5325 // Check if all windows with the window token are focusable.
5326 allWindowsAreFocusable = false;
5327 break;
5328 }
5329 }
5330
5331 if (!windowFound) {
5332 return FocusResult::NO_WINDOW;
5333 }
5334 if (!allWindowsAreFocusable) {
5335 return FocusResult::NOT_FOCUSABLE;
5336 }
5337 if (!visibleWindowFound) {
5338 return FocusResult::NOT_VISIBLE;
5339 }
5340
5341 return FocusResult::OK;
5342}
Garfield Tane84e6f92019-08-29 17:28:41 -07005343} // namespace android::inputdispatcher