blob: beacba3cf5757b6cfda6741697e5d1ecf72e51b4 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
Vishnu Nair958da932020-08-21 17:12:37 -0700255/**
256 * Find the entry in std::unordered_map by key and return the value as an optional.
257 */
258template <typename K, typename V>
259static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
260 auto it = map.find(key);
261 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
262}
263
chaviwaf87b3e2019-10-01 16:59:28 -0700264static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
265 if (first == second) {
266 return true;
267 }
268
269 if (first == nullptr || second == nullptr) {
270 return false;
271 }
272
273 return first->getToken() == second->getToken();
274}
275
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800276static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
277 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
278}
279
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000280static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
281 EventEntry* eventEntry,
282 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700283 if (inputTarget.useDefaultPointerTransform()) {
284 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000285 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700286 inputTargetFlags, transform,
287 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000288 }
289
290 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
291 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
292
293 PointerCoords pointerCoords[motionEntry.pointerCount];
294
295 // Use the first pointer information to normalize all other pointers. This could be any pointer
296 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 // uses the transform for the normalized pointer.
298 const ui::Transform& firstPointerTransform =
299 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
300 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000301
302 // Iterate through all pointers in the event to normalize against the first.
303 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
304 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
305 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700306 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 // First, apply the current pointer's transform to update the coordinates into
310 // window space.
311 pointerCoords[pointerIndex].transform(currTransform);
312 // Next, apply the inverse transform of the normalized coordinates so the
313 // current coordinates are transformed into the normalized coordinate space.
314 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 }
316
317 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800318 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
320 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
321 motionEntry.metaState, motionEntry.buttonState,
322 motionEntry.classification, motionEntry.edgeFlags,
323 motionEntry.xPrecision, motionEntry.yPrecision,
324 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
325 motionEntry.downTime, motionEntry.pointerCount,
326 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
327 0 /* yOffset */);
328
329 if (motionEntry.injectionState) {
330 combinedMotionEntry->injectionState = motionEntry.injectionState;
331 combinedMotionEntry->injectionState->refCount += 1;
332 }
333
334 std::unique_ptr<DispatchEntry> dispatchEntry =
335 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 inputTargetFlags, firstPointerTransform,
337 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 combinedMotionEntry->release();
339 return dispatchEntry;
340}
341
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700342static void addGestureMonitors(const std::vector<Monitor>& monitors,
343 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
344 float yOffset = 0) {
345 if (monitors.empty()) {
346 return;
347 }
348 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
349 for (const Monitor& monitor : monitors) {
350 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
351 }
352}
353
Garfield Tan15601662020-09-22 15:32:38 -0700354static status_t openInputChannelPair(const std::string& name,
355 std::shared_ptr<InputChannel>& serverChannel,
356 std::unique_ptr<InputChannel>& clientChannel) {
357 std::unique_ptr<InputChannel> uniqueServerChannel;
358 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
359
360 serverChannel = std::move(uniqueServerChannel);
361 return result;
362}
363
Vishnu Nair958da932020-08-21 17:12:37 -0700364const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
365 switch (result) {
366 case InputDispatcher::FocusResult::OK:
367 return "Ok";
368 case InputDispatcher::FocusResult::NO_WINDOW:
369 return "Window not found";
370 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
371 return "Window not focusable";
372 case InputDispatcher::FocusResult::NOT_VISIBLE:
373 return "Window not visible";
374 }
375}
376
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500377template <typename T>
378static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
379 if (lhs == nullptr && rhs == nullptr) {
380 return true;
381 }
382 if (lhs == nullptr || rhs == nullptr) {
383 return false;
384 }
385 return *lhs == *rhs;
386}
387
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388// --- InputDispatcher ---
389
Garfield Tan00f511d2019-06-12 16:55:40 -0700390InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
391 : mPolicy(policy),
392 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700393 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800394 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700395 mAppSwitchSawKeyDown(false),
396 mAppSwitchDueTime(LONG_LONG_MAX),
397 mNextUnblockedEvent(nullptr),
398 mDispatchEnabled(false),
399 mDispatchFrozen(false),
400 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800401 // mInTouchMode will be initialized by the WindowManager to the default device config.
402 // To avoid leaking stack in case that call never comes, and for tests,
403 // initialize it here anyways.
404 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700405 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800407 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800408
Yi Kong9b14ac62018-07-17 13:48:38 -0700409 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410
411 policy->getDispatcherConfiguration(&mConfig);
412}
413
414InputDispatcher::~InputDispatcher() {
415 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800416 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417
418 resetKeyRepeatLocked();
419 releasePendingEventLocked();
420 drainInboundQueueLocked();
421 }
422
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700423 while (!mConnectionsByFd.empty()) {
424 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700425 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 }
427}
428
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700429status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700430 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700431 return ALREADY_EXISTS;
432 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 mThread = std::make_unique<InputThread>(
434 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
435 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436}
437
438status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700439 if (mThread && mThread->isCallingThread()) {
440 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441 return INVALID_OPERATION;
442 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700443 mThread.reset();
444 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700445}
446
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447void InputDispatcher::dispatchOnce() {
448 nsecs_t nextWakeupTime = LONG_LONG_MAX;
449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800450 std::scoped_lock _l(mLock);
451 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
453 // Run a dispatch loop if there are no pending commands.
454 // The dispatch loop might enqueue commands to run afterwards.
455 if (!haveCommandsLocked()) {
456 dispatchOnceInnerLocked(&nextWakeupTime);
457 }
458
459 // Run all pending commands if there are any.
460 // If any commands were run then force the next poll to wake up immediately.
461 if (runCommandsLockedInterruptible()) {
462 nextWakeupTime = LONG_LONG_MIN;
463 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800464
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700465 // If we are still waiting for ack on some events,
466 // we might have to wake up earlier to check if an app is anr'ing.
467 const nsecs_t nextAnrCheck = processAnrsLocked();
468 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
469
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470 // We are about to enter an infinitely long sleep, because we have no commands or
471 // pending or queued events
472 if (nextWakeupTime == LONG_LONG_MAX) {
473 mDispatcherEnteredIdle.notify_all();
474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 } // release lock
476
477 // Wait for callback or timeout or wake. (make sure we round up, not down)
478 nsecs_t currentTime = now();
479 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
480 mLooper->pollOnce(timeoutMillis);
481}
482
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700483/**
484 * Check if any of the connections' wait queues have events that are too old.
485 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
486 * Return the time at which we should wake up next.
487 */
488nsecs_t InputDispatcher::processAnrsLocked() {
489 const nsecs_t currentTime = now();
490 nsecs_t nextAnrCheck = LONG_LONG_MAX;
491 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
492 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
493 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
494 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700495 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700496 return LONG_LONG_MIN;
497 } else {
498 // Keep waiting
499 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
500 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
501 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
502 }
503 }
504
505 // Check if any connection ANRs are due
506 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
507 if (currentTime < nextAnrCheck) { // most likely scenario
508 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
509 }
510
511 // If we reached here, we have an unresponsive connection.
512 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
513 if (connection == nullptr) {
514 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
515 return nextAnrCheck;
516 }
517 connection->responsive = false;
518 // Stop waking up for this unresponsive connection
519 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
520 onAnrLocked(connection);
521 return LONG_LONG_MIN;
522}
523
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500524std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700525 sp<InputWindowHandle> window = getWindowHandleLocked(token);
526 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500527 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700528 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500529 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700530}
531
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
533 nsecs_t currentTime = now();
534
Jeff Browndc5992e2014-04-11 01:27:26 -0700535 // Reset the key repeat timer whenever normal dispatch is suspended while the
536 // device is in a non-interactive state. This is to ensure that we abort a key
537 // repeat if the device is just coming out of sleep.
538 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 resetKeyRepeatLocked();
540 }
541
542 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
543 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100544 if (DEBUG_FOCUS) {
545 ALOGD("Dispatch frozen. Waiting some more.");
546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 return;
548 }
549
550 // Optimize latency of app switches.
551 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
552 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
553 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
554 if (mAppSwitchDueTime < *nextWakeupTime) {
555 *nextWakeupTime = mAppSwitchDueTime;
556 }
557
558 // Ready to start a new event.
559 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700560 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700561 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 if (isAppSwitchDue) {
563 // The inbound queue is empty so the app switch key we were waiting
564 // for will never arrive. Stop waiting for it.
565 resetPendingAppSwitchLocked(false);
566 isAppSwitchDue = false;
567 }
568
569 // Synthesize a key repeat if appropriate.
570 if (mKeyRepeatState.lastKeyEntry) {
571 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
572 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
573 } else {
574 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
575 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
576 }
577 }
578 }
579
580 // Nothing to do if there is no pending event.
581 if (!mPendingEvent) {
582 return;
583 }
584 } else {
585 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700586 mPendingEvent = mInboundQueue.front();
587 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800588 traceInboundQueueLengthLocked();
589 }
590
591 // Poke user activity for this event.
592 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700593 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 }
596
597 // Now we have an event to dispatch.
598 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700599 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700603 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700605 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 }
607
608 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700609 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 }
611
612 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700613 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700614 ConfigurationChangedEntry* typedEntry =
615 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
616 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700617 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 break;
619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700621 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700622 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
623 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700624 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700625 break;
626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100628 case EventEntry::Type::FOCUS: {
629 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
630 dispatchFocusLocked(currentTime, typedEntry);
631 done = true;
632 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
633 break;
634 }
635
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700636 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700637 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
638 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700639 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700640 resetPendingAppSwitchLocked(true);
641 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700642 } else if (dropReason == DropReason::NOT_DROPPED) {
643 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700644 }
645 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700646 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700647 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700649 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
650 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700651 }
652 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
653 break;
654 }
655
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700656 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700658 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
659 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700661 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700662 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700663 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700664 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
665 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 }
667 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
668 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
671
672 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700673 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700674 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
Michael Wright3a981722015-06-10 15:26:13 +0100676 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677
678 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
681}
682
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700683/**
684 * Return true if the events preceding this incoming motion event should be dropped
685 * Return false otherwise (the default behaviour)
686 */
687bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700688 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700689 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700690
691 // Optimize case where the current application is unresponsive and the user
692 // decides to touch a window in a different application.
693 // If the application takes too long to catch up then we drop all events preceding
694 // the touch into the other window.
695 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700696 int32_t displayId = motionEntry.displayId;
697 int32_t x = static_cast<int32_t>(
698 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
699 int32_t y = static_cast<int32_t>(
700 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
701 sp<InputWindowHandle> touchedWindowHandle =
702 findTouchedWindowAtLocked(displayId, x, y, nullptr);
703 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 touchedWindowHandle->getApplicationToken() !=
705 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700706 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 ALOGI("Pruning input queue because user touched a different application while waiting "
708 "for %s",
709 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700710 return true;
711 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712
713 // Alternatively, maybe there's a gesture monitor that could handle this event
714 std::vector<TouchedMonitor> gestureMonitors =
715 findTouchedGestureMonitorsLocked(displayId, {});
716 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
717 sp<Connection> connection =
718 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000719 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700720 // This monitor could take more input. Drop all events preceding this
721 // event, so that gesture monitor could get a chance to receive the stream
722 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
723 "responsive gesture monitor that may handle the event",
724 mAwaitedFocusedApplication->getName().c_str());
725 return true;
726 }
727 }
728 }
729
730 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
731 // yet been processed by some connections, the dispatcher will wait for these motion
732 // events to be processed before dispatching the key event. This is because these motion events
733 // may cause a new window to be launched, which the user might expect to receive focus.
734 // To prevent waiting forever for such events, just send the key to the currently focused window
735 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
736 ALOGD("Received a new pointer down event, stop waiting for events to process and "
737 "just send the pending key event to the focused window.");
738 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700739 }
740 return false;
741}
742
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700744 bool needWake = mInboundQueue.empty();
745 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 traceInboundQueueLengthLocked();
747
748 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700749 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 // Optimize app switch latency.
751 // If the application takes too long to catch up then we drop all events preceding
752 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700753 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700755 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700757 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700762 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 mAppSwitchSawKeyDown = false;
764 needWake = true;
765 }
766 }
767 }
768 break;
769 }
770
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700771 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700772 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
773 mNextUnblockedEvent = entry;
774 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100778 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700779 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
780 break;
781 }
782 case EventEntry::Type::CONFIGURATION_CHANGED:
783 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700784 // nothing to do
785 break;
786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788
789 return needWake;
790}
791
792void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
793 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700794 mRecentQueue.push_back(entry);
795 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
796 mRecentQueue.front()->release();
797 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799}
800
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700802 int32_t y, TouchState* touchState,
803 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700805 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
806 LOG_ALWAYS_FATAL(
807 "Must provide a valid touch state if adding portal windows or outside targets");
808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700810 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800811 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 const InputWindowInfo* windowInfo = windowHandle->getInfo();
813 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100814 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
816 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100817 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
818 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
819 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800821 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 if (portalToDisplayId != ADISPLAY_ID_NONE &&
823 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800824 if (addPortalWindows) {
825 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700826 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800827 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700828 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 // Found window.
832 return windowHandle;
833 }
834 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800835
Michael Wright44753b12020-07-08 13:48:11 +0100836 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700837 touchState->addOrUpdateWindow(windowHandle,
838 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
839 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 }
843 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700844 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845}
846
Garfield Tane84e6f92019-08-29 17:28:41 -0700847std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700848 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000849 std::vector<TouchedMonitor> touchedMonitors;
850
851 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
852 addGestureMonitors(monitors, touchedMonitors);
853 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
854 const InputWindowInfo* windowInfo = portalWindow->getInfo();
855 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
857 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000858 }
859 return touchedMonitors;
860}
861
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700862void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 const char* reason;
864 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 reason = "inbound event was dropped because the policy consumed it";
870 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::DISABLED:
872 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 ALOGI("Dropped event because input dispatch is disabled.");
874 }
875 reason = "inbound event was dropped because input dispatch is disabled";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 ALOGI("Dropped event because of pending overdue app switch.");
879 reason = "inbound event was dropped because of pending overdue app switch";
880 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700882 ALOGI("Dropped event because the current application is not responding and the user "
883 "has started interacting with a different application.");
884 reason = "inbound event was dropped because the current application is not responding "
885 "and the user has started interacting with a different application";
886 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 ALOGI("Dropped event because it is stale.");
889 reason = "inbound event was dropped because it is stale";
890 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 case DropReason::NOT_DROPPED: {
892 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 }
896
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700897 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700898 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
900 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700903 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
905 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
907 synthesizeCancelationEventsForAllConnectionsLocked(options);
908 } else {
909 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
910 synthesizeCancelationEventsForAllConnectionsLocked(options);
911 }
912 break;
913 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100914 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700915 case EventEntry::Type::CONFIGURATION_CHANGED:
916 case EventEntry::Type::DEVICE_RESET: {
917 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
918 break;
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
921}
922
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800923static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
925 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926}
927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700928bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
929 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
930 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
931 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932}
933
934bool InputDispatcher::isAppSwitchPendingLocked() {
935 return mAppSwitchDueTime != LONG_LONG_MAX;
936}
937
938void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
939 mAppSwitchDueTime = LONG_LONG_MAX;
940
941#if DEBUG_APP_SWITCH
942 if (handled) {
943 ALOGD("App switch has arrived.");
944 } else {
945 ALOGD("App switch was abandoned.");
946 }
947#endif
948}
949
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700951 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952}
953
954bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 return false;
957 }
958
959 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700960 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700961 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700963 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964
965 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700966 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 return true;
968}
969
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700970void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
971 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972}
973
974void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700975 while (!mInboundQueue.empty()) {
976 EventEntry* entry = mInboundQueue.front();
977 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 releaseInboundEventLocked(entry);
979 }
980 traceInboundQueueLengthLocked();
981}
982
983void InputDispatcher::releasePendingEventLocked() {
984 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700986 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 }
988}
989
990void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
991 InjectionState* injectionState = entry->injectionState;
992 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
993#if DEBUG_DISPATCH_CYCLE
994 ALOGD("Injected inbound event was dropped.");
995#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800996 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700999 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
1001 addRecentEventLocked(entry);
1002 entry->release();
1003}
1004
1005void InputDispatcher::resetKeyRepeatLocked() {
1006 if (mKeyRepeatState.lastKeyEntry) {
1007 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001008 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 }
1010}
1011
Garfield Tane84e6f92019-08-29 17:28:41 -07001012KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1014
1015 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001016 uint32_t policyFlags = entry->policyFlags &
1017 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 if (entry->refCount == 1) {
1019 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001020 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 entry->eventTime = currentTime;
1022 entry->policyFlags = policyFlags;
1023 entry->repeatCount += 1;
1024 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001026 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001027 entry->displayId, policyFlags, entry->action, entry->flags,
1028 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
1031 mKeyRepeatState.lastKeyEntry = newEntry;
1032 entry->release();
1033
1034 entry = newEntry;
1035 }
1036 entry->syntheticRepeat = true;
1037
1038 // Increment reference count since we keep a reference to the event in
1039 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1040 entry->refCount += 1;
1041
1042 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1043 return entry;
1044}
1045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1047 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001049 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050#endif
1051
1052 // Reset key repeating in case a keyboard device was added or removed or something.
1053 resetKeyRepeatLocked();
1054
1055 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001056 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1057 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001059 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 return true;
1061}
1062
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001063bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001065 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001066 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067#endif
1068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 options.deviceId = entry->deviceId;
1071 synthesizeCancelationEventsForAllConnectionsLocked(options);
1072 return true;
1073}
1074
Vishnu Nairad321cd2020-08-20 16:40:21 -07001075void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001076 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001077 if (mPendingEvent != nullptr) {
1078 // Move the pending event to the front of the queue. This will give the chance
1079 // for the pending event to get dispatched to the newly focused window
1080 mInboundQueue.push_front(mPendingEvent);
1081 mPendingEvent = nullptr;
1082 }
1083
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001084 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001085 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001086
1087 // This event should go to the front of the queue, but behind all other focus events
1088 // Find the last focus event, and insert right after it
1089 std::deque<EventEntry*>::reverse_iterator it =
1090 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1091 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1092
1093 // Maintain the order of focus events. Insert the entry after all other focus events.
1094 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001095}
1096
1097void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001098 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001099 if (channel == nullptr) {
1100 return; // Window has gone away
1101 }
1102 InputTarget target;
1103 target.inputChannel = channel;
1104 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1105 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001106 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1107 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001108 std::string reason = std::string("reason=").append(entry->reason);
1109 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001110 dispatchEventLocked(currentTime, entry, {target});
1111}
1112
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 if (!entry->dispatchInProgress) {
1117 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1118 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1119 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1120 if (mKeyRepeatState.lastKeyEntry &&
1121 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 // We have seen two identical key downs in a row which indicates that the device
1123 // driver is automatically generating key repeats itself. We take note of the
1124 // repeat here, but we disable our own next key repeat timer since it is clear that
1125 // we will not need to synthesize key repeats ourselves.
1126 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1127 resetKeyRepeatLocked();
1128 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1129 } else {
1130 // Not a repeat. Save key down state in case we do see a repeat later.
1131 resetKeyRepeatLocked();
1132 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1133 }
1134 mKeyRepeatState.lastKeyEntry = entry;
1135 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 resetKeyRepeatLocked();
1138 }
1139
1140 if (entry->repeatCount == 1) {
1141 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1142 } else {
1143 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1144 }
1145
1146 entry->dispatchInProgress = true;
1147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150
1151 // Handle case where the policy asked us to try again later last time.
1152 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1153 if (currentTime < entry->interceptKeyWakeupTime) {
1154 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1155 *nextWakeupTime = entry->interceptKeyWakeupTime;
1156 }
1157 return false; // wait until next wakeup
1158 }
1159 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1160 entry->interceptKeyWakeupTime = 0;
1161 }
1162
1163 // Give the policy a chance to intercept the key.
1164 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1165 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001166 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001167 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001168 sp<IBinder> focusedWindowToken =
1169 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1170 if (focusedWindowToken != nullptr) {
1171 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 }
1173 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001174 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 entry->refCount += 1;
1176 return false; // wait for the command to run
1177 } else {
1178 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1179 }
1180 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001181 if (*dropReason == DropReason::NOT_DROPPED) {
1182 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184 }
1185
1186 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001191 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 return true;
1193 }
1194
1195 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001196 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001198 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1200 return false;
1201 }
1202
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001203 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1205 return true;
1206 }
1207
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001208 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210
1211 // Dispatch the key.
1212 dispatchEventLocked(currentTime, entry, inputTargets);
1213 return true;
1214}
1215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001218 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1220 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001221 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1222 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1223 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224#endif
1225}
1226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1228 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001229 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 entry->dispatchInProgress = true;
1233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001234 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236
1237 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001238 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 return true;
1243 }
1244
1245 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1246
1247 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001248 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249
1250 bool conflictingPointerActions = false;
1251 int32_t injectionResult;
1252 if (isPointerEvent) {
1253 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 } else {
1258 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
1262 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1263 return false;
1264 }
1265
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001266 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001267 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1268 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1269 return true;
1270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001272 CancelationOptions::Mode mode(isPointerEvent
1273 ? CancelationOptions::CANCEL_POINTER_EVENTS
1274 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1275 CancelationOptions options(mode, "input event injection failed");
1276 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 return true;
1278 }
1279
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001280 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001281 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001283 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001284 std::unordered_map<int32_t, TouchState>::iterator it =
1285 mTouchStatesByDisplay.find(entry->displayId);
1286 if (it != mTouchStatesByDisplay.end()) {
1287 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001288 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001289 // The event has gone through these portal windows, so we add monitoring targets of
1290 // the corresponding displays as well.
1291 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001292 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001293 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001295 }
1296 }
1297 }
1298 }
1299
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 // Dispatch the motion.
1301 if (conflictingPointerActions) {
1302 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 synthesizeCancelationEventsForAllConnectionsLocked(options);
1305 }
1306 dispatchEventLocked(currentTime, entry, inputTargets);
1307 return true;
1308}
1309
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001310void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001312 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 ", policyFlags=0x%x, "
1314 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1315 "metaState=0x%x, buttonState=0x%x,"
1316 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001317 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1318 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1319 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 "x=%f, y=%f, pressure=%f, size=%f, "
1324 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1325 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1327 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1328 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 }
1337#endif
1338}
1339
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001340void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1341 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001342 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343#if DEBUG_DISPATCH_CYCLE
1344 ALOGD("dispatchEventToCurrentInputTargets");
1345#endif
1346
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001347 updateInteractionTokensLocked(*eventEntry, inputTargets);
1348
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001353 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001354 sp<Connection> connection =
1355 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001356 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001357 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001359 if (DEBUG_FOCUS) {
1360 ALOGD("Dropping event delivery to target with channel '%s' because it "
1361 "is no longer registered with the input dispatcher.",
1362 inputTarget.inputChannel->getName().c_str());
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 }
1366}
1367
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001368void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1369 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1370 // If the policy decides to close the app, we will get a channel removal event via
1371 // unregisterInputChannel, and will clean up the connection that way. We are already not
1372 // sending new pointers to the connection when it blocked, but focused events will continue to
1373 // pile up.
1374 ALOGW("Canceling events for %s because it is unresponsive",
1375 connection->inputChannel->getName().c_str());
1376 if (connection->status == Connection::STATUS_NORMAL) {
1377 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1378 "application not responding");
1379 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381}
1382
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001383void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001390 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001421bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1422 const char* focusedWindowName) {
1423 if (mAnrTracker.empty()) {
1424 // already processed all events that we waited for
1425 mKeyIsWaitingForEventsTimeout = std::nullopt;
1426 return false;
1427 }
1428
1429 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1430 // Start the timer
1431 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1432 "focus to change",
1433 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001434 mKeyIsWaitingForEventsTimeout = currentTime +
1435 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1436 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001437 return true;
1438 }
1439
1440 // We still have pending events, and already started the timer
1441 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1442 return true; // Still waiting
1443 }
1444
1445 // Waited too long, and some connection still hasn't processed all motions
1446 // Just send the key to the focused window
1447 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1448 focusedWindowName);
1449 mKeyIsWaitingForEventsTimeout = std::nullopt;
1450 return false;
1451}
1452
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001454 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 std::vector<InputTarget>& inputTargets,
1456 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
Tiger Huang721e26f2018-07-24 22:26:19 +08001459 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001460 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001461 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001462 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1463
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 // If there is no currently focused window and no focused application
1465 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001466 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1467 ALOGI("Dropping %s event because there is no focused window or focused application in "
1468 "display %" PRId32 ".",
1469 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001470 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 }
1472
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001473 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1474 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1475 // start interacting with another application via touch (app switch). This code can be removed
1476 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1477 // an app is expected to have a focused window.
1478 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1479 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1480 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001481 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1482 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1483 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001484 mAwaitedFocusedApplication = focusedApplicationHandle;
1485 ALOGW("Waiting because no window has focus but %s may eventually add a "
1486 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001487 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001488 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1489 return INPUT_EVENT_INJECTION_PENDING;
1490 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1491 // Already raised ANR. Drop the event
1492 ALOGE("Dropping %s event because there is no focused window",
1493 EventEntry::typeToString(entry.type));
1494 return INPUT_EVENT_INJECTION_FAILED;
1495 } else {
1496 // Still waiting for the focused window
1497 return INPUT_EVENT_INJECTION_PENDING;
1498 }
1499 }
1500
1501 // we have a valid, non-null focused window
1502 resetNoFocusedWindowTimeoutLocked();
1503
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001505 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001506 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001509 if (focusedWindowHandle->getInfo()->paused) {
1510 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1511 return INPUT_EVENT_INJECTION_PENDING;
1512 }
1513
1514 // If the event is a key event, then we must wait for all previous events to
1515 // complete before delivering it because previous events may have the
1516 // side-effect of transferring focus to a different window and we want to
1517 // ensure that the following keys are sent to the new window.
1518 //
1519 // Suppose the user touches a button in a window then immediately presses "A".
1520 // If the button causes a pop-up window to appear then we want to ensure that
1521 // the "A" key is delivered to the new pop-up window. This is because users
1522 // often anticipate pending UI changes when typing on a keyboard.
1523 // To obtain this behavior, we must serialize key events with respect to all
1524 // prior input events.
1525 if (entry.type == EventEntry::Type::KEY) {
1526 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1527 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1528 return INPUT_EVENT_INJECTION_PENDING;
1529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
1531
1532 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001533 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001534 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1535 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536
1537 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001538 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539}
1540
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001541/**
1542 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1543 * that are currently unresponsive.
1544 */
1545std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1546 const std::vector<TouchedMonitor>& monitors) const {
1547 std::vector<TouchedMonitor> responsiveMonitors;
1548 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1549 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1550 sp<Connection> connection = getConnectionLocked(
1551 monitor.monitor.inputChannel->getConnectionToken());
1552 if (connection == nullptr) {
1553 ALOGE("Could not find connection for monitor %s",
1554 monitor.monitor.inputChannel->getName().c_str());
1555 return false;
1556 }
1557 if (!connection->responsive) {
1558 ALOGW("Unresponsive monitor %s will not get the new gesture",
1559 connection->inputChannel->getName().c_str());
1560 return false;
1561 }
1562 return true;
1563 });
1564 return responsiveMonitors;
1565}
1566
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001568 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 std::vector<InputTarget>& inputTargets,
1570 nsecs_t* nextWakeupTime,
1571 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001572 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 enum InjectionPermission {
1574 INJECTION_PERMISSION_UNKNOWN,
1575 INJECTION_PERMISSION_GRANTED,
1576 INJECTION_PERMISSION_DENIED
1577 };
1578
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 // For security reasons, we defer updating the touch state until we are sure that
1580 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 int32_t displayId = entry.displayId;
1582 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1584
1585 // Update the touch state as needed based on the properties of the touch event.
1586 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1587 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001588 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1589 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001591 // Copy current touch state into tempTouchState.
1592 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1593 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001594 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001595 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001596 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1597 mTouchStatesByDisplay.find(displayId);
1598 if (oldStateIt != mTouchStatesByDisplay.end()) {
1599 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001600 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001601 }
1602
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001603 bool isSplit = tempTouchState.split;
1604 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1605 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1606 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001607 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1608 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1609 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1610 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1611 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 bool wrongDevice = false;
1614 if (newGesture) {
1615 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001616 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001617 ALOGI("Dropping event because a pointer for a different device is already down "
1618 "in display %" PRId32,
1619 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001620 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1622 switchedDevice = false;
1623 wrongDevice = true;
1624 goto Failed;
1625 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001626 tempTouchState.reset();
1627 tempTouchState.down = down;
1628 tempTouchState.deviceId = entry.deviceId;
1629 tempTouchState.source = entry.source;
1630 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001632 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001633 ALOGI("Dropping move event because a pointer for a different device is already active "
1634 "in display %" PRId32,
1635 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001636 // TODO: test multiple simultaneous input streams.
1637 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1638 switchedDevice = false;
1639 wrongDevice = true;
1640 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642
1643 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1644 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1645
Garfield Tan00f511d2019-06-12 16:55:40 -07001646 int32_t x;
1647 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001649 // Always dispatch mouse events to cursor position.
1650 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001651 x = int32_t(entry.xCursorPosition);
1652 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001653 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1655 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001656 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001657 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001658 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001659 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1660 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001661
1662 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001663 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001664 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 if (newTouchedWindowHandle != nullptr &&
1668 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001669 // New window supports splitting, but we should never split mouse events.
1670 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 } else if (isSplit) {
1672 // New window does not support splitting but we have already split events.
1673 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001674 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 }
1676
1677 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001678 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001680 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001681 }
1682
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001683 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1684 ALOGI("Not sending touch event to %s because it is paused",
1685 newTouchedWindowHandle->getName().c_str());
1686 newTouchedWindowHandle = nullptr;
1687 }
1688
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001689 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001690 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001691 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1692 if (!isResponsive) {
1693 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001694 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1695 newTouchedWindowHandle = nullptr;
1696 }
1697 }
1698
1699 // Also don't send the new touch event to unresponsive gesture monitors
1700 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1701
Michael Wright3dd60e22019-03-27 22:06:44 +00001702 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1703 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001704 "(%d, %d) in display %" PRId32 ".",
1705 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1707 goto Failed;
1708 }
1709
1710 if (newTouchedWindowHandle != nullptr) {
1711 // Set target flags.
1712 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1713 if (isSplit) {
1714 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001716 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1717 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1718 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1719 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1720 }
1721
1722 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001723 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1724 newHoverWindowHandle = nullptr;
1725 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001726 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001727 }
1728
1729 // Update the temporary touch state.
1730 BitSet32 pointerIds;
1731 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 pointerIds.markBit(pointerId);
1734 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001735 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001738 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 } else {
1740 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1741
1742 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001743 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001744 if (DEBUG_FOCUS) {
1745 ALOGD("Dropping event because the pointer is not down or we previously "
1746 "dropped the pointer down event in display %" PRId32,
1747 displayId);
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1750 goto Failed;
1751 }
1752
1753 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001755 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1757 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
1759 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001760 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001761 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1763 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001764 if (DEBUG_FOCUS) {
1765 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1766 oldTouchedWindowHandle->getName().c_str(),
1767 newTouchedWindowHandle->getName().c_str(), displayId);
1768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001770 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1771 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1772 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
1774 // Make a slippery entrance into the new window.
1775 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1776 isSplit = true;
1777 }
1778
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001779 int32_t targetFlags =
1780 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 if (isSplit) {
1782 targetFlags |= InputTarget::FLAG_SPLIT;
1783 }
1784 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1785 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1786 }
1787
1788 BitSet32 pointerIds;
1789 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001792 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794 }
1795 }
1796
1797 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001798 // Let the previous window know that the hover sequence is over, unless we already did it
1799 // when dispatching it as is to newTouchedWindowHandle.
1800 if (mLastHoverWindowHandle != nullptr &&
1801 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1802 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803#if DEBUG_HOVER
1804 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001807 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1808 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
1810
Garfield Tandf26e862020-07-01 20:18:19 -07001811 // Let the new window know that the hover sequence is starting, unless we already did it
1812 // when dispatching it as is to newTouchedWindowHandle.
1813 if (newHoverWindowHandle != nullptr &&
1814 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1815 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816#if DEBUG_HOVER
1817 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001820 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1821 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1822 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824 }
1825
1826 // Check permission to inject into all touched foreground windows and ensure there
1827 // is at least one touched foreground window.
1828 {
1829 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1832 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1835 injectionPermission = INJECTION_PERMISSION_DENIED;
1836 goto Failed;
1837 }
1838 }
1839 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001840 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001841 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001842 ALOGI("Dropping event because there is no touched foreground window in display "
1843 "%" PRId32 " or gesture monitor to receive it.",
1844 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1846 goto Failed;
1847 }
1848
1849 // Permission granted to injection into all touched foreground windows.
1850 injectionPermission = INJECTION_PERMISSION_GRANTED;
1851 }
1852
1853 // Check whether windows listening for outside touches are owned by the same UID. If it is
1854 // set the policy flag that we will not reveal coordinate information to this window.
1855 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1856 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001858 if (foregroundWindowHandle) {
1859 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1862 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1863 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001864 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1865 InputTarget::FLAG_ZERO_COORDS,
1866 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869 }
1870 }
1871 }
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 // If this is the first pointer going down and the touched window has a wallpaper
1874 // then also add the touched wallpaper windows so they are locked in for the duration
1875 // of the touch gesture.
1876 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1877 // engine only supports touch events. We would need to add a mechanism similar
1878 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1879 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1880 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001881 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001882 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001883 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001884 getWindowHandlesLocked(displayId);
1885 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001888 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001889 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 .addOrUpdateWindow(windowHandle,
1891 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1892 InputTarget::
1893 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1894 InputTarget::FLAG_DISPATCH_AS_IS,
1895 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897 }
1898 }
1899 }
1900
1901 // Success! Output targets.
1902 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1903
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001904 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001906 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 }
1908
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001910 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001911 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001912 }
1913
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // Drop the outside or hover touch windows since we will not care about them
1915 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001916 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917
1918Failed:
1919 // Check injection permission once and for all.
1920 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001921 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 injectionPermission = INJECTION_PERMISSION_GRANTED;
1923 } else {
1924 injectionPermission = INJECTION_PERMISSION_DENIED;
1925 }
1926 }
1927
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001928 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1929 return injectionResult;
1930 }
1931
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001933 if (!wrongDevice) {
1934 if (switchedDevice) {
1935 if (DEBUG_FOCUS) {
1936 ALOGD("Conflicting pointer actions: Switched to a different device.");
1937 }
1938 *outConflictingPointerActions = true;
1939 }
1940
1941 if (isHoverAction) {
1942 // Started hovering, therefore no longer down.
1943 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001944 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1946 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 *outConflictingPointerActions = true;
1949 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001950 tempTouchState.reset();
1951 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1952 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1953 tempTouchState.deviceId = entry.deviceId;
1954 tempTouchState.source = entry.source;
1955 tempTouchState.displayId = displayId;
1956 }
1957 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1958 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1959 // All pointers up or canceled.
1960 tempTouchState.reset();
1961 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1962 // First pointer went down.
1963 if (oldState && oldState->down) {
1964 if (DEBUG_FOCUS) {
1965 ALOGD("Conflicting pointer actions: Down received while already down.");
1966 }
1967 *outConflictingPointerActions = true;
1968 }
1969 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1970 // One pointer went up.
1971 if (isSplit) {
1972 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1973 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001975 for (size_t i = 0; i < tempTouchState.windows.size();) {
1976 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1977 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1978 touchedWindow.pointerIds.clearBit(pointerId);
1979 if (touchedWindow.pointerIds.isEmpty()) {
1980 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1981 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001984 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001986 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001988
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001989 // Save changes unless the action was scroll in which case the temporary touch
1990 // state was only valid for this one action.
1991 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1992 if (tempTouchState.displayId >= 0) {
1993 mTouchStatesByDisplay[displayId] = tempTouchState;
1994 } else {
1995 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001999 // Update hover state.
2000 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 return injectionResult;
2004}
2005
2006void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002007 int32_t targetFlags, BitSet32 pointerIds,
2008 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002009 std::vector<InputTarget>::iterator it =
2010 std::find_if(inputTargets.begin(), inputTargets.end(),
2011 [&windowHandle](const InputTarget& inputTarget) {
2012 return inputTarget.inputChannel->getConnectionToken() ==
2013 windowHandle->getToken();
2014 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002015
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002016 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002017
2018 if (it == inputTargets.end()) {
2019 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002020 std::shared_ptr<InputChannel> inputChannel =
2021 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002022 if (inputChannel == nullptr) {
2023 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2024 return;
2025 }
2026 inputTarget.inputChannel = inputChannel;
2027 inputTarget.flags = targetFlags;
2028 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2029 inputTargets.push_back(inputTarget);
2030 it = inputTargets.end() - 1;
2031 }
2032
2033 ALOG_ASSERT(it->flags == targetFlags);
2034 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2035
chaviw1ff3d1e2020-07-01 15:53:47 -07002036 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037}
2038
Michael Wright3dd60e22019-03-27 22:06:44 +00002039void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 int32_t displayId, float xOffset,
2041 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002042 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2043 mGlobalMonitorsByDisplay.find(displayId);
2044
2045 if (it != mGlobalMonitorsByDisplay.end()) {
2046 const std::vector<Monitor>& monitors = it->second;
2047 for (const Monitor& monitor : monitors) {
2048 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 }
2051}
2052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002053void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2054 float yOffset,
2055 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002056 InputTarget target;
2057 target.inputChannel = monitor.inputChannel;
2058 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002059 ui::Transform t;
2060 t.set(xOffset, yOffset);
2061 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 inputTargets.push_back(target);
2063}
2064
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 const InjectionState* injectionState) {
2067 if (injectionState &&
2068 (windowHandle == nullptr ||
2069 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2070 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002071 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002073 "owned by uid %d",
2074 injectionState->injectorPid, injectionState->injectorUid,
2075 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 } else {
2077 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080 return false;
2081 }
2082 return true;
2083}
2084
Robert Carrc9bf1d32020-04-13 17:21:08 -07002085/**
2086 * Indicate whether one window handle should be considered as obscuring
2087 * another window handle. We only check a few preconditions. Actually
2088 * checking the bounds is left to the caller.
2089 */
2090static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2091 const sp<InputWindowHandle>& otherHandle) {
2092 // Compare by token so cloned layers aren't counted
2093 if (haveSameToken(windowHandle, otherHandle)) {
2094 return false;
2095 }
2096 auto info = windowHandle->getInfo();
2097 auto otherInfo = otherHandle->getInfo();
2098 if (!otherInfo->visible) {
2099 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002100 } else if (info->ownerPid == otherInfo->ownerPid) {
2101 // If ownerPid is the same we don't generate occlusion events as there
2102 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002103 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002104 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002105 return false;
2106 } else if (otherInfo->displayId != info->displayId) {
2107 return false;
2108 }
2109 return true;
2110}
2111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002112bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2113 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002115 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002116 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002117 if (windowHandle == otherHandle) {
2118 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002121 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002122 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 return true;
2124 }
2125 }
2126 return false;
2127}
2128
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002129bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2130 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002131 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002132 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002133 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002134 if (windowHandle == otherHandle) {
2135 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002136 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002137 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002138 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002139 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002140 return true;
2141 }
2142 }
2143 return false;
2144}
2145
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002146std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002147 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002149 if (applicationHandle != nullptr) {
2150 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002151 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 } else {
2153 return applicationHandle->getName();
2154 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002155 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002156 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002158 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160}
2161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002162void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002163 if (eventEntry.type == EventEntry::Type::FOCUS) {
2164 // Focus events are passed to apps, but do not represent user activity.
2165 return;
2166 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002167 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002168 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002169 if (focusedWindowHandle != nullptr) {
2170 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002171 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002173 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174#endif
2175 return;
2176 }
2177 }
2178
2179 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002180 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002181 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2183 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 return;
2185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002187 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 eventType = USER_ACTIVITY_EVENT_TOUCH;
2189 }
2190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002192 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002193 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2194 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002195 return;
2196 }
2197 eventType = USER_ACTIVITY_EVENT_BUTTON;
2198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002200 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002201 case EventEntry::Type::CONFIGURATION_CHANGED:
2202 case EventEntry::Type::DEVICE_RESET: {
2203 LOG_ALWAYS_FATAL("%s events are not user activity",
2204 EventEntry::typeToString(eventEntry.type));
2205 break;
2206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
2208
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002209 std::unique_ptr<CommandEntry> commandEntry =
2210 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002213 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214}
2215
2216void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 const sp<Connection>& connection,
2218 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002219 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002220 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002222 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002223 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 ATRACE_NAME(message.c_str());
2225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#if DEBUG_DISPATCH_CYCLE
2227 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002228 "globalScaleFactor=%f, pointerIds=0x%x %s",
2229 connection->getInputChannelName().c_str(), inputTarget.flags,
2230 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2231 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232#endif
2233
2234 // Skip this event if the connection status is not normal.
2235 // We don't want to enqueue additional outbound events if the connection is broken.
2236 if (connection->status != Connection::STATUS_NORMAL) {
2237#if DEBUG_DISPATCH_CYCLE
2238 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002239 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240#endif
2241 return;
2242 }
2243
2244 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002245 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2246 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2247 "Entry type %s should not have FLAG_SPLIT",
2248 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002250 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002251 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 if (!splitMotionEntry) {
2255 return; // split event was dropped
2256 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002257 if (DEBUG_FOCUS) {
2258 ALOGD("channel '%s' ~ Split motion event.",
2259 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002260 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002261 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 splitMotionEntry->release();
2264 return;
2265 }
2266 }
2267
2268 // Not splitting. Enqueue dispatch entries for the event as is.
2269 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2270}
2271
2272void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 const sp<Connection>& connection,
2274 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002275 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002276 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002278 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002279 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002280 ATRACE_NAME(message.c_str());
2281 }
2282
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002283 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298
2299 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002300 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 startDispatchCycleLocked(currentTime, connection);
2302 }
2303}
2304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2306 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002307 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2311 connection->getInputChannelName().c_str(),
2312 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002313 ATRACE_NAME(message.c_str());
2314 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002315 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 if (!(inputTargetFlags & dispatchMode)) {
2317 return;
2318 }
2319 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2320
2321 // This is a new event.
2322 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002323 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002324 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2327 // different EventEntry than what was passed in.
2328 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002330 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002331 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002333 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002334 dispatchEntry->resolvedAction = keyEntry.action;
2335 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2338 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2341 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002343 return; // skip the inconsistent event
2344 }
2345 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002348 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002349 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002350 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2351 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2352 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2353 static_cast<int32_t>(IdGenerator::Source::OTHER);
2354 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2357 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2365 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002366 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002367 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002368 }
2369 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002370 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2371 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2374 "event",
2375 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002380 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2382 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2383 }
2384 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2385 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2389 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002391 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2392 "event",
2393 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395 return; // skip the inconsistent event
2396 }
2397
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002398 dispatchEntry->resolvedEventId =
2399 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2400 ? mIdGenerator.nextId()
2401 : motionEntry.id;
2402 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2403 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2404 ") to MotionEvent(id=0x%" PRIx32 ").",
2405 motionEntry.id, dispatchEntry->resolvedEventId);
2406 ATRACE_NAME(message.c_str());
2407 }
2408
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002409 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002410 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002411
2412 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002414 case EventEntry::Type::FOCUS: {
2415 break;
2416 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002417 case EventEntry::Type::CONFIGURATION_CHANGED:
2418 case EventEntry::Type::DEVICE_RESET: {
2419 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002420 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002421 break;
2422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
2424
2425 // Remember that we are waiting for this dispatch to complete.
2426 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002427 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
2429
2430 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002431 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002432 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002433}
2434
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002435/**
2436 * This function is purely for debugging. It helps us understand where the user interaction
2437 * was taking place. For example, if user is touching launcher, we will see a log that user
2438 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2439 * We will see both launcher and wallpaper in that list.
2440 * Once the interaction with a particular set of connections starts, no new logs will be printed
2441 * until the set of interacted connections changes.
2442 *
2443 * The following items are skipped, to reduce the logspam:
2444 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2445 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2446 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2447 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2448 * Both of those ACTION_UP events would not be logged
2449 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2450 * will not be logged. This is omitted to reduce the amount of data printed.
2451 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2452 * gesture monitor is the only connection receiving the remainder of the gesture.
2453 */
2454void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2455 const std::vector<InputTarget>& targets) {
2456 // Skip ACTION_UP events, and all events other than keys and motions
2457 if (entry.type == EventEntry::Type::KEY) {
2458 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2459 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2460 return;
2461 }
2462 } else if (entry.type == EventEntry::Type::MOTION) {
2463 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2464 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2465 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2466 return;
2467 }
2468 } else {
2469 return; // Not a key or a motion
2470 }
2471
2472 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2473 std::vector<sp<Connection>> newConnections;
2474 for (const InputTarget& target : targets) {
2475 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2476 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2477 continue; // Skip windows that receive ACTION_OUTSIDE
2478 }
2479
2480 sp<IBinder> token = target.inputChannel->getConnectionToken();
2481 sp<Connection> connection = getConnectionLocked(token);
2482 if (connection == nullptr || connection->monitor) {
2483 continue; // We only need to keep track of the non-monitor connections.
2484 }
2485 newConnectionTokens.insert(std::move(token));
2486 newConnections.emplace_back(connection);
2487 }
2488 if (newConnectionTokens == mInteractionConnectionTokens) {
2489 return; // no change
2490 }
2491 mInteractionConnectionTokens = newConnectionTokens;
2492
2493 std::string windowList;
2494 for (const sp<Connection>& connection : newConnections) {
2495 windowList += connection->getWindowName() + ", ";
2496 }
2497 std::string message = "Interaction with windows: " + windowList;
2498 if (windowList.empty()) {
2499 message += "<none>";
2500 }
2501 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2502}
2503
chaviwfd6d3512019-03-25 13:23:49 -07002504void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002505 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002506 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002507 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2508 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002509 return;
2510 }
2511
Vishnu Nairad321cd2020-08-20 16:40:21 -07002512 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2513 if (focusedToken == token) {
2514 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002515 return;
2516 }
2517
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002518 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2519 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002520 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002521 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522}
2523
2524void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002525 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002526 if (ATRACE_ENABLED()) {
2527 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002528 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002529 ATRACE_NAME(message.c_str());
2530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533#endif
2534
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002535 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2536 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002538 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002539 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002540 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541
2542 // Publish the event.
2543 status_t status;
2544 EventEntry* eventEntry = dispatchEntry->eventEntry;
2545 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002546 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002547 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2548 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002550 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002551 status =
2552 connection->inputPublisher
2553 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2554 keyEntry->deviceId, keyEntry->source,
2555 keyEntry->displayId, std::move(hmac),
2556 dispatchEntry->resolvedAction,
2557 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2558 keyEntry->scanCode, keyEntry->metaState,
2559 keyEntry->repeatCount, keyEntry->downTime,
2560 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002564 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002565 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 PointerCoords scaledCoords[MAX_POINTERS];
2568 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2569
chaviw82357092020-01-28 13:13:06 -08002570 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2572 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2573 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002574 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2576 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002577 // Don't apply window scale here since we don't want scale to affect raw
2578 // coordinates. The scale will be sent back to the client and applied
2579 // later when requesting relative coordinates.
2580 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2581 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 }
2583 usingCoords = scaledCoords;
2584 }
2585 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 // We don't want the dispatch target to know.
2587 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2588 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2589 scaledCoords[i].clear();
2590 }
2591 usingCoords = scaledCoords;
2592 }
2593 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002594
2595 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596
2597 // Publish the motion event.
2598 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002599 .publishMotionEvent(dispatchEntry->seq,
2600 dispatchEntry->resolvedEventId,
2601 motionEntry->deviceId, motionEntry->source,
2602 motionEntry->displayId, std::move(hmac),
2603 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604 motionEntry->actionButton,
2605 dispatchEntry->resolvedFlags,
2606 motionEntry->edgeFlags, motionEntry->metaState,
2607 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002608 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002609 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002610 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002611 motionEntry->yPrecision,
2612 motionEntry->xCursorPosition,
2613 motionEntry->yCursorPosition,
2614 motionEntry->downTime, motionEntry->eventTime,
2615 motionEntry->pointerCount,
2616 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002617 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 break;
2619 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002620 case EventEntry::Type::FOCUS: {
2621 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2622 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002623 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002624 focusEntry->hasFocus,
2625 mInTouchMode);
2626 break;
2627 }
2628
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002629 case EventEntry::Type::CONFIGURATION_CHANGED:
2630 case EventEntry::Type::DEVICE_RESET: {
2631 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2632 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002633 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 }
2636
2637 // Check the result.
2638 if (status) {
2639 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002640 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 "This is unexpected because the wait queue is empty, so the pipe "
2643 "should be empty and we shouldn't have any problems writing an "
2644 "event to it, status=%d",
2645 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2647 } else {
2648 // Pipe is full and we are waiting for the app to finish process some events
2649 // before sending more events to it.
2650#if DEBUG_DISPATCH_CYCLE
2651 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 "waiting for the application to catch up",
2653 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
2656 } else {
2657 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 "status=%d",
2659 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2661 }
2662 return;
2663 }
2664
2665 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002666 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2667 connection->outboundQueue.end(),
2668 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002669 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002670 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002671 if (connection->responsive) {
2672 mAnrTracker.insert(dispatchEntry->timeoutTime,
2673 connection->inputChannel->getConnectionToken());
2674 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002675 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677}
2678
chaviw09c8d2d2020-08-24 15:48:26 -07002679std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2680 size_t size;
2681 switch (event.type) {
2682 case VerifiedInputEvent::Type::KEY: {
2683 size = sizeof(VerifiedKeyEvent);
2684 break;
2685 }
2686 case VerifiedInputEvent::Type::MOTION: {
2687 size = sizeof(VerifiedMotionEvent);
2688 break;
2689 }
2690 }
2691 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2692 return mHmacKeyManager.sign(start, size);
2693}
2694
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002695const std::array<uint8_t, 32> InputDispatcher::getSignature(
2696 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2697 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2698 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2699 // Only sign events up and down events as the purely move events
2700 // are tied to their up/down counterparts so signing would be redundant.
2701 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2702 verifiedEvent.actionMasked = actionMasked;
2703 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002704 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002705 }
2706 return INVALID_HMAC;
2707}
2708
2709const std::array<uint8_t, 32> InputDispatcher::getSignature(
2710 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2711 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2712 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2713 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002714 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002715}
2716
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 const sp<Connection>& connection, uint32_t seq,
2719 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720#if DEBUG_DISPATCH_CYCLE
2721 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723#endif
2724
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 if (connection->status == Connection::STATUS_BROKEN ||
2726 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 return;
2728 }
2729
2730 // Notify other system components and prepare to start the next dispatch cycle.
2731 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2732}
2733
2734void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 const sp<Connection>& connection,
2736 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737#if DEBUG_DISPATCH_CYCLE
2738 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740#endif
2741
2742 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002743 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002744 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002745 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002746 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
2748 // The connection appears to be unrecoverably broken.
2749 // Ignore already broken or zombie connections.
2750 if (connection->status == Connection::STATUS_NORMAL) {
2751 connection->status = Connection::STATUS_BROKEN;
2752
2753 if (notify) {
2754 // Notify other system components.
2755 onDispatchCycleBrokenLocked(currentTime, connection);
2756 }
2757 }
2758}
2759
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002760void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2761 while (!queue.empty()) {
2762 DispatchEntry* dispatchEntry = queue.front();
2763 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002764 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
2766}
2767
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002768void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002770 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
2772 delete dispatchEntry;
2773}
2774
2775int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2776 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2777
2778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002779 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002781 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 "fd=%d, events=0x%x",
2784 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 return 0; // remove the callback
2786 }
2787
2788 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002789 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2791 if (!(events & ALOOPER_EVENT_INPUT)) {
2792 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 "events=0x%x",
2794 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 return 1;
2796 }
2797
2798 nsecs_t currentTime = now();
2799 bool gotOne = false;
2800 status_t status;
2801 for (;;) {
2802 uint32_t seq;
2803 bool handled;
2804 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2805 if (status) {
2806 break;
2807 }
2808 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2809 gotOne = true;
2810 }
2811 if (gotOne) {
2812 d->runCommandsLockedInterruptible();
2813 if (status == WOULD_BLOCK) {
2814 return 1;
2815 }
2816 }
2817
2818 notify = status != DEAD_OBJECT || !connection->monitor;
2819 if (notify) {
2820 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
2823 } else {
2824 // Monitor channels are never explicitly unregistered.
2825 // We do it automatically when the remote endpoint is closed so don't warn
2826 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002827 const bool stillHaveWindowHandle =
2828 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2829 nullptr;
2830 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 if (notify) {
2832 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 "events=0x%x",
2834 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 }
2836 }
2837
Garfield Tan15601662020-09-22 15:32:38 -07002838 // Remove the channel.
2839 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842}
2843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002846 for (const auto& pair : mConnectionsByFd) {
2847 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
2849}
2850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002852 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002853 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2854 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2855}
2856
2857void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2858 const CancelationOptions& options,
2859 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2860 for (const auto& it : monitorsByDisplay) {
2861 const std::vector<Monitor>& monitors = it.second;
2862 for (const Monitor& monitor : monitors) {
2863 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002864 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002865 }
2866}
2867
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002869 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002870 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002871 if (connection == nullptr) {
2872 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002874
2875 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876}
2877
2878void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2879 const sp<Connection>& connection, const CancelationOptions& options) {
2880 if (connection->status == Connection::STATUS_BROKEN) {
2881 return;
2882 }
2883
2884 nsecs_t currentTime = now();
2885
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002886 std::vector<EventEntry*> cancelationEvents =
2887 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002889 if (cancelationEvents.empty()) {
2890 return;
2891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002893 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2894 "with reality: %s, mode=%d.",
2895 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2896 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002898
2899 InputTarget target;
2900 sp<InputWindowHandle> windowHandle =
2901 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2902 if (windowHandle != nullptr) {
2903 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002904 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002905 target.globalScaleFactor = windowInfo->globalScaleFactor;
2906 }
2907 target.inputChannel = connection->inputChannel;
2908 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2909
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002910 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2911 EventEntry* cancelationEventEntry = cancelationEvents[i];
2912 switch (cancelationEventEntry->type) {
2913 case EventEntry::Type::KEY: {
2914 logOutboundKeyDetails("cancel - ",
2915 static_cast<const KeyEntry&>(*cancelationEventEntry));
2916 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002918 case EventEntry::Type::MOTION: {
2919 logOutboundMotionDetails("cancel - ",
2920 static_cast<const MotionEntry&>(*cancelationEventEntry));
2921 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002923 case EventEntry::Type::FOCUS: {
2924 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2925 break;
2926 }
2927 case EventEntry::Type::CONFIGURATION_CHANGED:
2928 case EventEntry::Type::DEVICE_RESET: {
2929 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2930 EventEntry::typeToString(cancelationEventEntry->type));
2931 break;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
2934
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002935 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2936 target, InputTarget::FLAG_DISPATCH_AS_IS);
2937
2938 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002940
2941 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942}
2943
Svet Ganov5d3bc372020-01-26 23:11:07 -08002944void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2945 const sp<Connection>& connection) {
2946 if (connection->status == Connection::STATUS_BROKEN) {
2947 return;
2948 }
2949
2950 nsecs_t currentTime = now();
2951
2952 std::vector<EventEntry*> downEvents =
2953 connection->inputState.synthesizePointerDownEvents(currentTime);
2954
2955 if (downEvents.empty()) {
2956 return;
2957 }
2958
2959#if DEBUG_OUTBOUND_EVENT_DETAILS
2960 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2961 connection->getInputChannelName().c_str(), downEvents.size());
2962#endif
2963
2964 InputTarget target;
2965 sp<InputWindowHandle> windowHandle =
2966 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2967 if (windowHandle != nullptr) {
2968 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002969 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002970 target.globalScaleFactor = windowInfo->globalScaleFactor;
2971 }
2972 target.inputChannel = connection->inputChannel;
2973 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2974
2975 for (EventEntry* downEventEntry : downEvents) {
2976 switch (downEventEntry->type) {
2977 case EventEntry::Type::MOTION: {
2978 logOutboundMotionDetails("down - ",
2979 static_cast<const MotionEntry&>(*downEventEntry));
2980 break;
2981 }
2982
2983 case EventEntry::Type::KEY:
2984 case EventEntry::Type::FOCUS:
2985 case EventEntry::Type::CONFIGURATION_CHANGED:
2986 case EventEntry::Type::DEVICE_RESET: {
2987 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2988 EventEntry::typeToString(downEventEntry->type));
2989 break;
2990 }
2991 }
2992
2993 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2994 target, InputTarget::FLAG_DISPATCH_AS_IS);
2995
2996 downEventEntry->release();
2997 }
2998
2999 startDispatchCycleLocked(currentTime, connection);
3000}
3001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003003 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 ALOG_ASSERT(pointerIds.value != 0);
3005
3006 uint32_t splitPointerIndexMap[MAX_POINTERS];
3007 PointerProperties splitPointerProperties[MAX_POINTERS];
3008 PointerCoords splitPointerCoords[MAX_POINTERS];
3009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003010 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 uint32_t splitPointerCount = 0;
3012
3013 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003016 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 uint32_t pointerId = uint32_t(pointerProperties.id);
3018 if (pointerIds.hasBit(pointerId)) {
3019 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3020 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3021 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 splitPointerCount += 1;
3024 }
3025 }
3026
3027 if (splitPointerCount != pointerIds.count()) {
3028 // This is bad. We are missing some of the pointers that we expected to deliver.
3029 // Most likely this indicates that we received an ACTION_MOVE events that has
3030 // different pointer ids than we expected based on the previous ACTION_DOWN
3031 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3032 // in this way.
3033 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 "we expected there to be %d pointers. This probably means we received "
3035 "a broken sequence of pointer ids from the input device.",
3036 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003037 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
3039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3043 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3045 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003046 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 uint32_t pointerId = uint32_t(pointerProperties.id);
3048 if (pointerIds.hasBit(pointerId)) {
3049 if (pointerIds.count() == 1) {
3050 // The first/last pointer went down/up.
3051 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 ? AMOTION_EVENT_ACTION_DOWN
3053 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 } else {
3055 // A secondary pointer went down/up.
3056 uint32_t splitPointerIndex = 0;
3057 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3058 splitPointerIndex += 1;
3059 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003060 action = maskedAction |
3061 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 }
3063 } else {
3064 // An unrelated pointer changed.
3065 action = AMOTION_EVENT_ACTION_MOVE;
3066 }
3067 }
3068
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 int32_t newId = mIdGenerator.nextId();
3070 if (ATRACE_ENABLED()) {
3071 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3072 ") to MotionEvent(id=0x%" PRIx32 ").",
3073 originalMotionEntry.id, newId);
3074 ATRACE_NAME(message.c_str());
3075 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003076 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003077 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3078 originalMotionEntry.source, originalMotionEntry.displayId,
3079 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 originalMotionEntry.actionButton, originalMotionEntry.flags,
3081 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3082 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3083 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3084 originalMotionEntry.xCursorPosition,
3085 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003086 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 if (originalMotionEntry.injectionState) {
3089 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 splitMotionEntry->injectionState->refCount += 1;
3091 }
3092
3093 return splitMotionEntry;
3094}
3095
3096void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3097#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003098 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099#endif
3100
3101 bool needWake;
3102 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003103 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104
Prabir Pradhan42611e02018-11-27 14:04:02 -08003105 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003106 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 needWake = enqueueInboundEventLocked(newEntry);
3108 } // release lock
3109
3110 if (needWake) {
3111 mLooper->wake();
3112 }
3113}
3114
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003115/**
3116 * If one of the meta shortcuts is detected, process them here:
3117 * Meta + Backspace -> generate BACK
3118 * Meta + Enter -> generate HOME
3119 * This will potentially overwrite keyCode and metaState.
3120 */
3121void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003123 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3124 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3125 if (keyCode == AKEYCODE_DEL) {
3126 newKeyCode = AKEYCODE_BACK;
3127 } else if (keyCode == AKEYCODE_ENTER) {
3128 newKeyCode = AKEYCODE_HOME;
3129 }
3130 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003134 keyCode = newKeyCode;
3135 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3136 }
3137 } else if (action == AKEY_EVENT_ACTION_UP) {
3138 // In order to maintain a consistent stream of up and down events, check to see if the key
3139 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3140 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003141 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003142 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003143 auto replacementIt = mReplacedKeys.find(replacement);
3144 if (replacementIt != mReplacedKeys.end()) {
3145 keyCode = replacementIt->second;
3146 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003147 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3148 }
3149 }
3150}
3151
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3153#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3155 "policyFlags=0x%x, action=0x%x, "
3156 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3157 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3158 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3159 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160#endif
3161 if (!validateKeyEvent(args->action)) {
3162 return;
3163 }
3164
3165 uint32_t policyFlags = args->policyFlags;
3166 int32_t flags = args->flags;
3167 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003168 // InputDispatcher tracks and generates key repeats on behalf of
3169 // whatever notifies it, so repeatCount should always be set to 0
3170 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3172 policyFlags |= POLICY_FLAG_VIRTUAL;
3173 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 if (policyFlags & POLICY_FLAG_FUNCTION) {
3176 metaState |= AMETA_FUNCTION_ON;
3177 }
3178
3179 policyFlags |= POLICY_FLAG_TRUSTED;
3180
Michael Wright78f24442014-08-06 15:55:28 -07003181 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003182 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003183
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003185 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003186 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3187 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188
Michael Wright2b3c3302018-03-02 17:19:13 +00003189 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003191 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3192 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 bool needWake;
3197 { // acquire lock
3198 mLock.lock();
3199
3200 if (shouldSendKeyToInputFilterLocked(args)) {
3201 mLock.unlock();
3202
3203 policyFlags |= POLICY_FLAG_FILTERED;
3204 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3205 return; // event was consumed by the filter
3206 }
3207
3208 mLock.lock();
3209 }
3210
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003212 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 args->displayId, policyFlags, args->action, flags, keyCode,
3214 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
3216 needWake = enqueueInboundEventLocked(newEntry);
3217 mLock.unlock();
3218 } // release lock
3219
3220 if (needWake) {
3221 mLooper->wake();
3222 }
3223}
3224
3225bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3226 return mInputFilterEnabled;
3227}
3228
3229void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3230#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003231 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3232 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003233 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3234 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003235 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003236 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3237 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3238 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3239 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 for (uint32_t i = 0; i < args->pointerCount; i++) {
3241 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 "x=%f, y=%f, pressure=%f, size=%f, "
3243 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3244 "orientation=%f",
3245 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3251 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3252 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3253 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3254 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
3256#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3258 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 return;
3260 }
3261
3262 uint32_t policyFlags = args->policyFlags;
3263 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003264
3265 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003266 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003267 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3268 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003269 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 bool needWake;
3273 { // acquire lock
3274 mLock.lock();
3275
3276 if (shouldSendMotionToInputFilterLocked(args)) {
3277 mLock.unlock();
3278
3279 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003280 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003281 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3282 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003283 args->metaState, args->buttonState, args->classification, transform,
3284 args->xPrecision, args->yPrecision, args->xCursorPosition,
3285 args->yCursorPosition, args->downTime, args->eventTime,
3286 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
3288 policyFlags |= POLICY_FLAG_FILTERED;
3289 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3290 return; // event was consumed by the filter
3291 }
3292
3293 mLock.lock();
3294 }
3295
3296 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003297 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003298 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003299 args->displayId, policyFlags, args->action, args->actionButton,
3300 args->flags, args->metaState, args->buttonState,
3301 args->classification, args->edgeFlags, args->xPrecision,
3302 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3303 args->downTime, args->pointerCount, args->pointerProperties,
3304 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
3306 needWake = enqueueInboundEventLocked(newEntry);
3307 mLock.unlock();
3308 } // release lock
3309
3310 if (needWake) {
3311 mLooper->wake();
3312 }
3313}
3314
3315bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003316 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317}
3318
3319void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3320#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003321 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 "switchMask=0x%08x",
3323 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324#endif
3325
3326 uint32_t policyFlags = args->policyFlags;
3327 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329}
3330
3331void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3332#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3334 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335#endif
3336
3337 bool needWake;
3338 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003339 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340
Prabir Pradhan42611e02018-11-27 14:04:02 -08003341 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003342 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 needWake = enqueueInboundEventLocked(newEntry);
3344 } // release lock
3345
3346 if (needWake) {
3347 mLooper->wake();
3348 }
3349}
3350
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3352 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003353 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354#if DEBUG_INBOUND_EVENT_DETAILS
3355 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003356 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3357 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003359 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
3361 policyFlags |= POLICY_FLAG_INJECTED;
3362 if (hasInjectionPermission(injectorPid, injectorUid)) {
3363 policyFlags |= POLICY_FLAG_TRUSTED;
3364 }
3365
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003366 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003369 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3370 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003371 if (!validateKeyEvent(action)) {
3372 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003375 int32_t flags = incomingKey.getFlags();
3376 int32_t keyCode = incomingKey.getKeyCode();
3377 int32_t metaState = incomingKey.getMetaState();
3378 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003380 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003381 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003382 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3383 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3384 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3387 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003388 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389
3390 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3391 android::base::Timer t;
3392 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3393 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3394 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3395 std::to_string(t.duration().count()).c_str());
3396 }
3397 }
3398
3399 mLock.lock();
3400 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003401 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3402 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003403 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3404 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003405 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 injectedEntries.push(injectedEntry);
3407 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 }
3409
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 case AINPUT_EVENT_TYPE_MOTION: {
3411 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3412 int32_t action = motionEvent->getAction();
3413 size_t pointerCount = motionEvent->getPointerCount();
3414 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3415 int32_t actionButton = motionEvent->getActionButton();
3416 int32_t displayId = motionEvent->getDisplayId();
3417 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3418 return INPUT_EVENT_INJECTION_FAILED;
3419 }
3420
3421 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3422 nsecs_t eventTime = motionEvent->getEventTime();
3423 android::base::Timer t;
3424 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3425 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3426 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3427 std::to_string(t.duration().count()).c_str());
3428 }
3429 }
3430
3431 mLock.lock();
3432 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3433 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3434 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003435 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3436 motionEvent->getSource(), motionEvent->getDisplayId(),
3437 policyFlags, action, actionButton, motionEvent->getFlags(),
3438 motionEvent->getMetaState(), motionEvent->getButtonState(),
3439 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3440 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003441 motionEvent->getRawXCursorPosition(),
3442 motionEvent->getRawYCursorPosition(),
3443 motionEvent->getDownTime(), uint32_t(pointerCount),
3444 pointerProperties, samplePointerCoords,
3445 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 injectedEntries.push(injectedEntry);
3447 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3448 sampleEventTimes += 1;
3449 samplePointerCoords += pointerCount;
3450 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003451 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003452 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 motionEvent->getDisplayId(), policyFlags, action,
3454 actionButton, motionEvent->getFlags(),
3455 motionEvent->getMetaState(), motionEvent->getButtonState(),
3456 motionEvent->getClassification(),
3457 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3458 motionEvent->getYPrecision(),
3459 motionEvent->getRawXCursorPosition(),
3460 motionEvent->getRawYCursorPosition(),
3461 motionEvent->getDownTime(), uint32_t(pointerCount),
3462 pointerProperties, samplePointerCoords,
3463 motionEvent->getXOffset(), motionEvent->getYOffset());
3464 injectedEntries.push(nextInjectedEntry);
3465 }
3466 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003470 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 }
3473
3474 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3475 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3476 injectionState->injectionIsAsync = true;
3477 }
3478
3479 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003480 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
3482 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003483 while (!injectedEntries.empty()) {
3484 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3485 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487
3488 mLock.unlock();
3489
3490 if (needWake) {
3491 mLooper->wake();
3492 }
3493
3494 int32_t injectionResult;
3495 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003496 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3499 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3500 } else {
3501 for (;;) {
3502 injectionResult = injectionState->injectionResult;
3503 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3504 break;
3505 }
3506
3507 nsecs_t remainingTimeout = endTime - now();
3508 if (remainingTimeout <= 0) {
3509#if DEBUG_INJECTION
3510 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512#endif
3513 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3514 break;
3515 }
3516
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003517 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3521 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 while (injectionState->pendingForegroundDispatches != 0) {
3523#if DEBUG_INJECTION
3524 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526#endif
3527 nsecs_t remainingTimeout = endTime - now();
3528 if (remainingTimeout <= 0) {
3529#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3531 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532#endif
3533 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3534 break;
3535 }
3536
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539 }
3540 }
3541
3542 injectionState->release();
3543 } // release lock
3544
3545#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003546 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003547 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548#endif
3549
3550 return injectionResult;
3551}
3552
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003553std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003554 std::array<uint8_t, 32> calculatedHmac;
3555 std::unique_ptr<VerifiedInputEvent> result;
3556 switch (event.getType()) {
3557 case AINPUT_EVENT_TYPE_KEY: {
3558 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3559 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3560 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003561 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003562 break;
3563 }
3564 case AINPUT_EVENT_TYPE_MOTION: {
3565 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3566 VerifiedMotionEvent verifiedMotionEvent =
3567 verifiedMotionEventFromMotionEvent(motionEvent);
3568 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003569 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003570 break;
3571 }
3572 default: {
3573 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3574 return nullptr;
3575 }
3576 }
3577 if (calculatedHmac == INVALID_HMAC) {
3578 return nullptr;
3579 }
3580 if (calculatedHmac != event.getHmac()) {
3581 return nullptr;
3582 }
3583 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003584}
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 return injectorUid == 0 ||
3588 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589}
3590
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003591void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 InjectionState* injectionState = entry->injectionState;
3593 if (injectionState) {
3594#if DEBUG_INJECTION
3595 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 "injectorPid=%d, injectorUid=%d",
3597 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598#endif
3599
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 // Log the outcome since the injector did not wait for the injection result.
3602 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 case INPUT_EVENT_INJECTION_SUCCEEDED:
3604 ALOGV("Asynchronous input event injection succeeded.");
3605 break;
3606 case INPUT_EVENT_INJECTION_FAILED:
3607 ALOGW("Asynchronous input event injection failed.");
3608 break;
3609 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3610 ALOGW("Asynchronous input event injection permission denied.");
3611 break;
3612 case INPUT_EVENT_INJECTION_TIMED_OUT:
3613 ALOGW("Asynchronous input event injection timed out.");
3614 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616 }
3617
3618 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003619 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621}
3622
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003623void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 InjectionState* injectionState = entry->injectionState;
3625 if (injectionState) {
3626 injectionState->pendingForegroundDispatches += 1;
3627 }
3628}
3629
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003630void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 InjectionState* injectionState = entry->injectionState;
3632 if (injectionState) {
3633 injectionState->pendingForegroundDispatches -= 1;
3634
3635 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003636 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638 }
3639}
3640
Vishnu Nairad321cd2020-08-20 16:40:21 -07003641const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003642 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003643 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3644 auto it = mWindowHandlesByDisplay.find(displayId);
3645 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003646}
3647
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003649 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003650 if (windowHandleToken == nullptr) {
3651 return nullptr;
3652 }
3653
Arthur Hungb92218b2018-08-14 12:00:21 +08003654 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003655 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003656 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003657 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003658 return windowHandle;
3659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003662 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663}
3664
Vishnu Nairad321cd2020-08-20 16:40:21 -07003665sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3666 int displayId) const {
3667 if (windowHandleToken == nullptr) {
3668 return nullptr;
3669 }
3670
3671 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3672 if (windowHandle->getToken() == windowHandleToken) {
3673 return windowHandle;
3674 }
3675 }
3676 return nullptr;
3677}
3678
3679sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3680 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3681 return getWindowHandleLocked(focusedToken, displayId);
3682}
3683
Mady Mellor017bcd12020-06-23 19:12:00 +00003684bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3685 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003686 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003687 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003688 if (handle->getId() == windowHandle->getId() &&
3689 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003690 if (windowHandle->getInfo()->displayId != it.first) {
3691 ALOGE("Found window %s in display %" PRId32
3692 ", but it should belong to display %" PRId32,
3693 windowHandle->getName().c_str(), it.first,
3694 windowHandle->getInfo()->displayId);
3695 }
3696 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699 }
3700 return false;
3701}
3702
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003703bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3704 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3705 const bool noInputChannel =
3706 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3707 if (connection != nullptr && noInputChannel) {
3708 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3709 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3710 return false;
3711 }
3712
3713 if (connection == nullptr) {
3714 if (!noInputChannel) {
3715 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3716 }
3717 return false;
3718 }
3719 if (!connection->responsive) {
3720 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3721 return false;
3722 }
3723 return true;
3724}
3725
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003726std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3727 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003728 size_t count = mInputChannelsByToken.count(token);
3729 if (count == 0) {
3730 return nullptr;
3731 }
3732 return mInputChannelsByToken.at(token);
3733}
3734
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003735void InputDispatcher::updateWindowHandlesForDisplayLocked(
3736 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3737 if (inputWindowHandles.empty()) {
3738 // Remove all handles on a display if there are no windows left.
3739 mWindowHandlesByDisplay.erase(displayId);
3740 return;
3741 }
3742
3743 // Since we compare the pointer of input window handles across window updates, we need
3744 // to make sure the handle object for the same window stays unchanged across updates.
3745 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003746 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003747 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003748 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003749 }
3750
3751 std::vector<sp<InputWindowHandle>> newHandles;
3752 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3753 if (!handle->updateInfo()) {
3754 // handle no longer valid
3755 continue;
3756 }
3757
3758 const InputWindowInfo* info = handle->getInfo();
3759 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3760 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3761 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003762 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3763 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3764 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003765 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003766 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003767 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003768 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003769 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003770 }
3771
3772 if (info->displayId != displayId) {
3773 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3774 handle->getName().c_str(), displayId, info->displayId);
3775 continue;
3776 }
3777
Robert Carredd13602020-04-13 17:24:34 -07003778 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3779 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003780 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003781 oldHandle->updateFrom(handle);
3782 newHandles.push_back(oldHandle);
3783 } else {
3784 newHandles.push_back(handle);
3785 }
3786 }
3787
3788 // Insert or replace
3789 mWindowHandlesByDisplay[displayId] = newHandles;
3790}
3791
Arthur Hung72d8dc32020-03-28 00:48:39 +00003792void InputDispatcher::setInputWindows(
3793 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3794 { // acquire lock
3795 std::scoped_lock _l(mLock);
3796 for (auto const& i : handlesPerDisplay) {
3797 setInputWindowsLocked(i.second, i.first);
3798 }
3799 }
3800 // Wake up poll loop since it may need to make new input dispatching choices.
3801 mLooper->wake();
3802}
3803
Arthur Hungb92218b2018-08-14 12:00:21 +08003804/**
3805 * Called from InputManagerService, update window handle list by displayId that can receive input.
3806 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3807 * If set an empty list, remove all handles from the specific display.
3808 * For focused handle, check if need to change and send a cancel event to previous one.
3809 * For removed handle, check if need to send a cancel event if already in touch.
3810 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003811void InputDispatcher::setInputWindowsLocked(
3812 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003813 if (DEBUG_FOCUS) {
3814 std::string windowList;
3815 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3816 windowList += iwh->getName() + " ";
3817 }
3818 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003821 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3822 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3823 const bool noInputWindow =
3824 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3825 if (noInputWindow && window->getToken() != nullptr) {
3826 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3827 window->getName().c_str());
3828 window->releaseChannel();
3829 }
3830 }
3831
Arthur Hung72d8dc32020-03-28 00:48:39 +00003832 // Copy old handles for release if they are no longer present.
3833 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834
Arthur Hung72d8dc32020-03-28 00:48:39 +00003835 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003836
Vishnu Nair958da932020-08-21 17:12:37 -07003837 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3838 if (mLastHoverWindowHandle &&
3839 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3840 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003841 mLastHoverWindowHandle = nullptr;
3842 }
3843
Vishnu Nair958da932020-08-21 17:12:37 -07003844 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3845 if (focusedToken) {
3846 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3847 if (result != FocusResult::OK) {
3848 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3849 }
3850 }
3851
3852 std::optional<FocusRequest> focusRequest =
3853 getOptionalValueByKey(mPendingFocusRequests, displayId);
3854 if (focusRequest) {
3855 // If the window from the pending request is now visible, provide it focus.
3856 FocusResult result = handleFocusRequestLocked(*focusRequest);
3857 if (result != FocusResult::NOT_VISIBLE) {
3858 // Drop the request if we were able to change the focus or we cannot change
3859 // it for another reason.
3860 mPendingFocusRequests.erase(displayId);
3861 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003864 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3865 mTouchStatesByDisplay.find(displayId);
3866 if (stateIt != mTouchStatesByDisplay.end()) {
3867 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003868 for (size_t i = 0; i < state.windows.size();) {
3869 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003870 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003871 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003872 ALOGD("Touched window was removed: %s in display %" PRId32,
3873 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003874 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003875 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003876 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3877 if (touchedInputChannel != nullptr) {
3878 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3879 "touched window was removed");
3880 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003882 state.windows.erase(state.windows.begin() + i);
3883 } else {
3884 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 }
3886 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003887 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003888
Arthur Hung72d8dc32020-03-28 00:48:39 +00003889 // Release information for windows that are no longer present.
3890 // This ensures that unused input channels are released promptly.
3891 // Otherwise, they might stick around until the window handle is destroyed
3892 // which might not happen until the next GC.
3893 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003894 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003895 if (DEBUG_FOCUS) {
3896 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003897 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003898 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003899 }
chaviw291d88a2019-02-14 10:33:58 -08003900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901}
3902
3903void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003904 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003905 if (DEBUG_FOCUS) {
3906 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3907 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3908 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003909 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003910 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911
Chris Yea209fde2020-07-22 13:54:51 -07003912 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003913 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003914
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003915 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
3916 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003917 }
3918
Chris Yea209fde2020-07-22 13:54:51 -07003919 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003920 if (inputApplicationHandle != nullptr) {
3921 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3922 } else {
3923 mFocusedApplicationHandlesByDisplay.erase(displayId);
3924 }
3925
3926 // No matter what the old focused application was, stop waiting on it because it is
3927 // no longer focused.
3928 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 } // release lock
3930
3931 // Wake up poll loop since it may need to make new input dispatching choices.
3932 mLooper->wake();
3933}
3934
Tiger Huang721e26f2018-07-24 22:26:19 +08003935/**
3936 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3937 * the display not specified.
3938 *
3939 * We track any unreleased events for each window. If a window loses the ability to receive the
3940 * released event, we will send a cancel event to it. So when the focused display is changed, we
3941 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3942 * display. The display-specified events won't be affected.
3943 */
3944void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003945 if (DEBUG_FOCUS) {
3946 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3947 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003948 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003949 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003950
3951 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003952 sp<IBinder> oldFocusedWindowToken =
3953 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3954 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003955 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003956 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003957 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 CancelationOptions
3959 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3960 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003961 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003962 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3963 }
3964 }
3965 mFocusedDisplayId = displayId;
3966
Chris Ye3c2d6f52020-08-09 10:39:48 -07003967 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003968 sp<IBinder> newFocusedWindowToken =
3969 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3970 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003971
Vishnu Nairad321cd2020-08-20 16:40:21 -07003972 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003973 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003974 if (!mFocusedWindowTokenByDisplay.empty()) {
3975 ALOGE("But another display has a focused window\n%s",
3976 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003977 }
3978 }
3979 }
3980
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003981 if (DEBUG_FOCUS) {
3982 logDispatchStateLocked();
3983 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003984 } // release lock
3985
3986 // Wake up poll loop since it may need to make new input dispatching choices.
3987 mLooper->wake();
3988}
3989
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003991 if (DEBUG_FOCUS) {
3992 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994
3995 bool changed;
3996 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003997 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
3999 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4000 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004001 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 }
4003
4004 if (mDispatchEnabled && !enabled) {
4005 resetAndDropEverythingLocked("dispatcher is being disabled");
4006 }
4007
4008 mDispatchEnabled = enabled;
4009 mDispatchFrozen = frozen;
4010 changed = true;
4011 } else {
4012 changed = false;
4013 }
4014
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004015 if (DEBUG_FOCUS) {
4016 logDispatchStateLocked();
4017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 } // release lock
4019
4020 if (changed) {
4021 // Wake up poll loop since it may need to make new input dispatching choices.
4022 mLooper->wake();
4023 }
4024}
4025
4026void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004027 if (DEBUG_FOCUS) {
4028 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
4031 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004032 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
4034 if (mInputFilterEnabled == enabled) {
4035 return;
4036 }
4037
4038 mInputFilterEnabled = enabled;
4039 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4040 } // release lock
4041
4042 // Wake up poll loop since there might be work to do to drop everything.
4043 mLooper->wake();
4044}
4045
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004046void InputDispatcher::setInTouchMode(bool inTouchMode) {
4047 std::scoped_lock lock(mLock);
4048 mInTouchMode = inTouchMode;
4049}
4050
chaviwfbe5d9c2018-12-26 12:23:37 -08004051bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4052 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004053 if (DEBUG_FOCUS) {
4054 ALOGD("Trivial transfer to same window.");
4055 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004056 return true;
4057 }
4058
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004060 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
chaviwfbe5d9c2018-12-26 12:23:37 -08004062 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4063 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004064 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004065 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 return false;
4067 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004068 if (DEBUG_FOCUS) {
4069 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4070 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004073 if (DEBUG_FOCUS) {
4074 ALOGD("Cannot transfer focus because windows are on different displays.");
4075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 return false;
4077 }
4078
4079 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004080 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4081 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004082 for (size_t i = 0; i < state.windows.size(); i++) {
4083 const TouchedWindow& touchedWindow = state.windows[i];
4084 if (touchedWindow.windowHandle == fromWindowHandle) {
4085 int32_t oldTargetFlags = touchedWindow.targetFlags;
4086 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004088 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 int32_t newTargetFlags = oldTargetFlags &
4091 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4092 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004093 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Jeff Brownf086ddb2014-02-11 14:28:48 -08004095 found = true;
4096 goto Found;
4097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004103 if (DEBUG_FOCUS) {
4104 ALOGD("Focus transfer failed because from window did not have focus.");
4105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 return false;
4107 }
4108
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004109 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4110 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004111 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004112 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 CancelationOptions
4114 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4115 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004117 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004120 if (DEBUG_FOCUS) {
4121 logDispatchStateLocked();
4122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 } // release lock
4124
4125 // Wake up poll loop since it may need to make new input dispatching choices.
4126 mLooper->wake();
4127 return true;
4128}
4129
4130void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004131 if (DEBUG_FOCUS) {
4132 ALOGD("Resetting and dropping all events (%s).", reason);
4133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
4135 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4136 synthesizeCancelationEventsForAllConnectionsLocked(options);
4137
4138 resetKeyRepeatLocked();
4139 releasePendingEventLocked();
4140 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004141 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004143 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004144 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004146 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147}
4148
4149void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 dumpDispatchStateLocked(dump);
4152
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 std::istringstream stream(dump);
4154 std::string line;
4155
4156 while (std::getline(stream, line, '\n')) {
4157 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159}
4160
Vishnu Nairad321cd2020-08-20 16:40:21 -07004161std::string InputDispatcher::dumpFocusedWindowsLocked() {
4162 if (mFocusedWindowTokenByDisplay.empty()) {
4163 return INDENT "FocusedWindows: <none>\n";
4164 }
4165
4166 std::string dump;
4167 dump += INDENT "FocusedWindows:\n";
4168 for (auto& it : mFocusedWindowTokenByDisplay) {
4169 const int32_t displayId = it.first;
4170 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4171 if (windowHandle) {
4172 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4173 windowHandle->getName().c_str());
4174 } else {
4175 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4176 " has focused token without a window'\n",
4177 displayId);
4178 }
4179 }
4180 return dump;
4181}
4182
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004184 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4185 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4186 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004187 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Tiger Huang721e26f2018-07-24 22:26:19 +08004189 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4190 dump += StringPrintf(INDENT "FocusedApplications:\n");
4191 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4192 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004193 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004194 const std::chrono::duration timeout =
4195 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004197 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004198 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004201 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004203
Vishnu Nairad321cd2020-08-20 16:40:21 -07004204 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004206 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004208 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4209 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 state.displayId, toString(state.down), toString(state.split),
4212 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004213 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004215 for (size_t i = 0; i < state.windows.size(); i++) {
4216 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 dump += StringPrintf(INDENT4
4218 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4219 i, touchedWindow.windowHandle->getName().c_str(),
4220 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004221 }
4222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004224 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004225 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004226 dump += INDENT3 "Portal windows:\n";
4227 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004228 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4230 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004231 }
4232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237
Arthur Hungb92218b2018-08-14 12:00:21 +08004238 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004240 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004241 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004242 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004243 dump += INDENT2 "Windows:\n";
4244 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004245 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004246 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247
Arthur Hungb92218b2018-08-14 12:00:21 +08004248 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004249 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4250 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004251 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004253 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004254 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 i, windowInfo->name.c_str(), windowInfo->displayId,
4256 windowInfo->portalToDisplayId,
4257 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004258 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 toString(windowInfo->hasWallpaper),
4260 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004261 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004262 static_cast<int32_t>(windowInfo->type),
4263 windowInfo->frameLeft, windowInfo->frameTop,
4264 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004265 windowInfo->globalScaleFactor,
4266 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004267 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004268 dump += StringPrintf(", inputFeatures=%s",
4269 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004270 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4271 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004273 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004274 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004275 }
4276 } else {
4277 dump += INDENT2 "Windows: <none>\n";
4278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004281 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283
Michael Wright3dd60e22019-03-27 22:06:44 +00004284 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004285 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004286 const std::vector<Monitor>& monitors = it.second;
4287 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4288 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 }
4290 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004291 const std::vector<Monitor>& monitors = it.second;
4292 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4293 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004296 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 }
4298
4299 nsecs_t currentTime = now();
4300
4301 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004302 if (!mRecentQueue.empty()) {
4303 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4304 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004305 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004307 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
4313 // Dump event currently being dispatched.
4314 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004315 dump += INDENT "PendingEvent:\n";
4316 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004318 dump += StringPrintf(", age=%" PRId64 "ms\n",
4319 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004321 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323
4324 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004325 if (!mInboundQueue.empty()) {
4326 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4327 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004328 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004330 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004336 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004338 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4339 const KeyReplacement& replacement = pair.first;
4340 int32_t newKeyCode = pair.second;
4341 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004342 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004343 }
4344 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004345 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004346 }
4347
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004348 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004349 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004350 for (const auto& pair : mConnectionsByFd) {
4351 const sp<Connection>& connection = pair.second;
4352 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004353 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004354 pair.first, connection->getInputChannelName().c_str(),
4355 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004356 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004358 if (!connection->outboundQueue.empty()) {
4359 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4360 connection->outboundQueue.size());
4361 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 dump.append(INDENT4);
4363 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004364 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4365 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004367 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004373 if (!connection->waitQueue.empty()) {
4374 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4375 connection->waitQueue.size());
4376 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004377 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004380 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004382 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004383 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004386 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
4388 }
4389 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392
4393 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004394 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4395 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004397 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 }
4399
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004400 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004401 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4402 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4403 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404}
4405
Michael Wright3dd60e22019-03-27 22:06:44 +00004406void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4407 const size_t numMonitors = monitors.size();
4408 for (size_t i = 0; i < numMonitors; i++) {
4409 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004410 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004411 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4412 dump += "\n";
4413 }
4414}
4415
Garfield Tan15601662020-09-22 15:32:38 -07004416base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4417 const std::string& name) {
4418#if DEBUG_CHANNEL_CREATION
4419 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420#endif
4421
Garfield Tan15601662020-09-22 15:32:38 -07004422 std::shared_ptr<InputChannel> serverChannel;
4423 std::unique_ptr<InputChannel> clientChannel;
4424 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4425
4426 if (result) {
4427 return base::Error(result) << "Failed to open input channel pair with name " << name;
4428 }
4429
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004431 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004432 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
Garfield Tan15601662020-09-22 15:32:38 -07004434 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004435 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004436 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4439 } // release lock
4440
4441 // Wake the looper because some connections have changed.
4442 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004443 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444}
4445
Garfield Tan15601662020-09-22 15:32:38 -07004446base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4447 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4448 std::shared_ptr<InputChannel> serverChannel;
4449 std::unique_ptr<InputChannel> clientChannel;
4450 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4451 if (result) {
4452 return base::Error(result) << "Failed to open input channel pair with name " << name;
4453 }
4454
Michael Wright3dd60e22019-03-27 22:06:44 +00004455 { // acquire lock
4456 std::scoped_lock _l(mLock);
4457
4458 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004459 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4460 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004461 }
4462
Garfield Tan15601662020-09-22 15:32:38 -07004463 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004464
Garfield Tan15601662020-09-22 15:32:38 -07004465 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004466 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004467 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004468
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 auto& monitorsByDisplay =
4470 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004471 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004472
4473 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004474 }
Garfield Tan15601662020-09-22 15:32:38 -07004475
Michael Wright3dd60e22019-03-27 22:06:44 +00004476 // Wake the looper because some connections have changed.
4477 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004478 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004479}
4480
Garfield Tan15601662020-09-22 15:32:38 -07004481status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004483 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484
Garfield Tan15601662020-09-22 15:32:38 -07004485 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 if (status) {
4487 return status;
4488 }
4489 } // release lock
4490
4491 // Wake the poll loop because removing the connection may have changed the current
4492 // synchronization state.
4493 mLooper->wake();
4494 return OK;
4495}
4496
Garfield Tan15601662020-09-22 15:32:38 -07004497status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4498 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004499 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004500 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004501 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 return BAD_VALUE;
4503 }
4504
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004505 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004506 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004507
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004509 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004512 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513
4514 nsecs_t currentTime = now();
4515 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4516
4517 connection->status = Connection::STATUS_ZOMBIE;
4518 return OK;
4519}
4520
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004521void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4522 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4523 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004524}
4525
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004527 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004528 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004529 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004530 std::vector<Monitor>& monitors = it->second;
4531 const size_t numMonitors = monitors.size();
4532 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004533 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004534 monitors.erase(monitors.begin() + i);
4535 break;
4536 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004537 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004538 if (monitors.empty()) {
4539 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004540 } else {
4541 ++it;
4542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 }
4544}
4545
Michael Wright3dd60e22019-03-27 22:06:44 +00004546status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4547 { // acquire lock
4548 std::scoped_lock _l(mLock);
4549 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4550
4551 if (!foundDisplayId) {
4552 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4553 return BAD_VALUE;
4554 }
4555 int32_t displayId = foundDisplayId.value();
4556
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004557 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4558 mTouchStatesByDisplay.find(displayId);
4559 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004560 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4561 return BAD_VALUE;
4562 }
4563
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004564 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004565 std::optional<int32_t> foundDeviceId;
4566 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004567 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004568 foundDeviceId = state.deviceId;
4569 }
4570 }
4571 if (!foundDeviceId || !state.down) {
4572 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004574 return BAD_VALUE;
4575 }
4576 int32_t deviceId = foundDeviceId.value();
4577
4578 // Send cancel events to all the input channels we're stealing from.
4579 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004580 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004581 options.deviceId = deviceId;
4582 options.displayId = displayId;
4583 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004584 std::shared_ptr<InputChannel> channel =
4585 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004586 if (channel != nullptr) {
4587 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4588 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004589 }
4590 // Then clear the current touch state so we stop dispatching to them as well.
4591 state.filterNonMonitors();
4592 }
4593 return OK;
4594}
4595
Michael Wright3dd60e22019-03-27 22:06:44 +00004596std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4597 const sp<IBinder>& token) {
4598 for (const auto& it : mGestureMonitorsByDisplay) {
4599 const std::vector<Monitor>& monitors = it.second;
4600 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004601 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004602 return it.first;
4603 }
4604 }
4605 }
4606 return std::nullopt;
4607}
4608
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004610 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004611 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004612 }
4613
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004614 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004615 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004616 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004617 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 }
4619 }
Robert Carr4e670e52018-08-15 13:26:12 -07004620
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004621 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622}
4623
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004624void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004626 removeByValue(mConnectionsByFd, connection);
4627}
4628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004629void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4630 const sp<Connection>& connection, uint32_t seq,
4631 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004632 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4633 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 commandEntry->connection = connection;
4635 commandEntry->eventTime = currentTime;
4636 commandEntry->seq = seq;
4637 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004638 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639}
4640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4642 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004646 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4647 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004649 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650}
4651
Vishnu Nairad321cd2020-08-20 16:40:21 -07004652void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4653 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004654 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4655 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004656 commandEntry->oldToken = oldToken;
4657 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004658 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004659}
4660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4662 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4663 // is already healthy again. Don't raise ANR in this situation
4664 if (connection->waitQueue.empty()) {
4665 ALOGI("Not raising ANR because the connection %s has recovered",
4666 connection->inputChannel->getName().c_str());
4667 return;
4668 }
4669 /**
4670 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4671 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4672 * has changed. This could cause newer entries to time out before the already dispatched
4673 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4674 * processes the events linearly. So providing information about the oldest entry seems to be
4675 * most useful.
4676 */
4677 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4678 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4679 std::string reason =
4680 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4681 connection->inputChannel->getName().c_str(),
4682 ns2ms(currentWait),
4683 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004685 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4686 reason);
4687
4688 std::unique_ptr<CommandEntry> commandEntry =
4689 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4690 commandEntry->inputApplicationHandle = nullptr;
4691 commandEntry->inputChannel = connection->inputChannel;
4692 commandEntry->reason = std::move(reason);
4693 postCommandLocked(std::move(commandEntry));
4694}
4695
Chris Yea209fde2020-07-22 13:54:51 -07004696void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4698 application->getName().c_str());
4699
4700 updateLastAnrStateLocked(application, reason);
4701
4702 std::unique_ptr<CommandEntry> commandEntry =
4703 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4704 commandEntry->inputApplicationHandle = application;
4705 commandEntry->inputChannel = nullptr;
4706 commandEntry->reason = std::move(reason);
4707 postCommandLocked(std::move(commandEntry));
4708}
4709
4710void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4711 const std::string& reason) {
4712 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4713 updateLastAnrStateLocked(windowLabel, reason);
4714}
4715
Chris Yea209fde2020-07-22 13:54:51 -07004716void InputDispatcher::updateLastAnrStateLocked(
4717 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4719 updateLastAnrStateLocked(windowLabel, reason);
4720}
4721
4722void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4723 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004725 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 struct tm tm;
4727 localtime_r(&t, &tm);
4728 char timestr[64];
4729 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004730 mLastAnrState.clear();
4731 mLastAnrState += INDENT "ANR:\n";
4732 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4734 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004735 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736}
4737
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004738void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 mLock.unlock();
4740
4741 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4742
4743 mLock.lock();
4744}
4745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 sp<Connection> connection = commandEntry->connection;
4748
4749 if (connection->status != Connection::STATUS_ZOMBIE) {
4750 mLock.unlock();
4751
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004752 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
4754 mLock.lock();
4755 }
4756}
4757
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004759 sp<IBinder> oldToken = commandEntry->oldToken;
4760 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004761 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004762 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004763 mLock.lock();
4764}
4765
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004766void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004767 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004768 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 mLock.unlock();
4770
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004771 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004772 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773
4774 mLock.lock();
4775
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004776 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4778 } else {
4779 // stop waking up for events in this connection, it is already not responding
4780 sp<Connection> connection = getConnectionLocked(token);
4781 if (connection == nullptr) {
4782 return;
4783 }
4784 cancelEventsForAnrLocked(connection);
4785 }
4786}
4787
Chris Yea209fde2020-07-22 13:54:51 -07004788void InputDispatcher::extendAnrTimeoutsLocked(
4789 const std::shared_ptr<InputApplicationHandle>& application,
4790 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 sp<Connection> connection = getConnectionLocked(connectionToken);
4792 if (connection == nullptr) {
4793 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4794 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004795 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796 mAwaitedFocusedApplication = application;
4797 } else {
4798 // It's also possible that the connection already disappeared. No action necessary.
4799 }
4800 return;
4801 }
4802
4803 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004804 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805
4806 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004807 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 for (DispatchEntry* entry : connection->waitQueue) {
4809 if (newTimeout >= entry->timeoutTime) {
4810 // Already removed old entries when connection was marked unresponsive
4811 entry->timeoutTime = newTimeout;
4812 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4813 }
4814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815}
4816
4817void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4818 CommandEntry* commandEntry) {
4819 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004820 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821
4822 mLock.unlock();
4823
Michael Wright2b3c3302018-03-02 17:19:13 +00004824 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004826 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 : nullptr;
4828 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004829 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4830 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833
4834 mLock.lock();
4835
4836 if (delay < 0) {
4837 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4838 } else if (!delay) {
4839 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4840 } else {
4841 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4842 entry->interceptKeyWakeupTime = now() + delay;
4843 }
4844 entry->release();
4845}
4846
chaviwfd6d3512019-03-25 13:23:49 -07004847void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4848 mLock.unlock();
4849 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4850 mLock.lock();
4851}
4852
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853/**
4854 * Connection is responsive if it has no events in the waitQueue that are older than the
4855 * current time.
4856 */
4857static bool isConnectionResponsive(const Connection& connection) {
4858 const nsecs_t currentTime = now();
4859 for (const DispatchEntry* entry : connection.waitQueue) {
4860 if (entry->timeoutTime < currentTime) {
4861 return false;
4862 }
4863 }
4864 return true;
4865}
4866
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004867void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004869 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004871 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872
4873 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004874 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004875 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004876 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004878 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004879 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004880 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004881 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4882 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004883 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004884 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004885
4886 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004887 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004888 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4889 restartEvent =
4890 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004891 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004892 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4893 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4894 handled);
4895 } else {
4896 restartEvent = false;
4897 }
4898
4899 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004900 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004901 // contents of the wait queue to have been drained, so we need to double-check
4902 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004903 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4904 if (dispatchEntryIt != connection->waitQueue.end()) {
4905 dispatchEntry = *dispatchEntryIt;
4906 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004907 mAnrTracker.erase(dispatchEntry->timeoutTime,
4908 connection->inputChannel->getConnectionToken());
4909 if (!connection->responsive) {
4910 connection->responsive = isConnectionResponsive(*connection);
4911 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004912 traceWaitQueueLength(connection);
4913 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004914 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004915 traceOutboundQueueLength(connection);
4916 } else {
4917 releaseDispatchEntry(dispatchEntry);
4918 }
4919 }
4920
4921 // Start the next dispatch cycle for this connection.
4922 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
4925bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004926 DispatchEntry* dispatchEntry,
4927 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004928 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004929 if (!handled) {
4930 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004931 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004932 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004933 return false;
4934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004936 // Get the fallback key state.
4937 // Clear it out after dispatching the UP.
4938 int32_t originalKeyCode = keyEntry->keyCode;
4939 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4940 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4941 connection->inputState.removeFallbackKey(originalKeyCode);
4942 }
4943
4944 if (handled || !dispatchEntry->hasForegroundTarget()) {
4945 // If the application handles the original key for which we previously
4946 // generated a fallback or if the window is not a foreground window,
4947 // then cancel the associated fallback key, if any.
4948 if (fallbackKeyCode != -1) {
4949 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004951 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004952 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4953 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4954 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004956 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004957 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958
4959 mLock.unlock();
4960
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004961 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004962 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
4964 mLock.lock();
4965
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004966 // Cancel the fallback key.
4967 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969 "application handled the original non-fallback key "
4970 "or is no longer a foreground target, "
4971 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 options.keyCode = fallbackKeyCode;
4973 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975 connection->inputState.removeFallbackKey(originalKeyCode);
4976 }
4977 } else {
4978 // If the application did not handle a non-fallback key, first check
4979 // that we are in a good state to perform unhandled key event processing
4980 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004981 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004984 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985 "since this is not an initial down. "
4986 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4987 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004989 return false;
4990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004992 // Dispatch the unhandled key to the policy.
4993#if DEBUG_OUTBOUND_EVENT_DETAILS
4994 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4996 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004997#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004998 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004999
5000 mLock.unlock();
5001
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005002 bool fallback =
5003 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5004 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005005
5006 mLock.lock();
5007
5008 if (connection->status != Connection::STATUS_NORMAL) {
5009 connection->inputState.removeFallbackKey(originalKeyCode);
5010 return false;
5011 }
5012
5013 // Latch the fallback keycode for this key on an initial down.
5014 // The fallback keycode cannot change at any other point in the lifecycle.
5015 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005017 fallbackKeyCode = event.getKeyCode();
5018 } else {
5019 fallbackKeyCode = AKEYCODE_UNKNOWN;
5020 }
5021 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5022 }
5023
5024 ALOG_ASSERT(fallbackKeyCode != -1);
5025
5026 // Cancel the fallback key if the policy decides not to send it anymore.
5027 // We will continue to dispatch the key to the policy but we will no
5028 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5030 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005031#if DEBUG_OUTBOUND_EVENT_DETAILS
5032 if (fallback) {
5033 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034 "as a fallback for %d, but on the DOWN it had requested "
5035 "to send %d instead. Fallback canceled.",
5036 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005037 } else {
5038 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005039 "but on the DOWN it had requested to send %d. "
5040 "Fallback canceled.",
5041 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005042 }
5043#endif
5044
5045 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5046 "canceling fallback, policy no longer desires it");
5047 options.keyCode = fallbackKeyCode;
5048 synthesizeCancelationEventsForConnectionLocked(connection, options);
5049
5050 fallback = false;
5051 fallbackKeyCode = AKEYCODE_UNKNOWN;
5052 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005053 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005054 }
5055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056
5057#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005058 {
5059 std::string msg;
5060 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5061 connection->inputState.getFallbackKeys();
5062 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005065 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005066 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005067 }
5068#endif
5069
5070 if (fallback) {
5071 // Restart the dispatch cycle using the fallback key.
5072 keyEntry->eventTime = event.getEventTime();
5073 keyEntry->deviceId = event.getDeviceId();
5074 keyEntry->source = event.getSource();
5075 keyEntry->displayId = event.getDisplayId();
5076 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5077 keyEntry->keyCode = fallbackKeyCode;
5078 keyEntry->scanCode = event.getScanCode();
5079 keyEntry->metaState = event.getMetaState();
5080 keyEntry->repeatCount = event.getRepeatCount();
5081 keyEntry->downTime = event.getDownTime();
5082 keyEntry->syntheticRepeat = false;
5083
5084#if DEBUG_OUTBOUND_EVENT_DETAILS
5085 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005086 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5087 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005088#endif
5089 return true; // restart the event
5090 } else {
5091#if DEBUG_OUTBOUND_EVENT_DETAILS
5092 ALOGD("Unhandled key event: No fallback key.");
5093#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005094
5095 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005096 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 }
5098 }
5099 return false;
5100}
5101
5102bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005103 DispatchEntry* dispatchEntry,
5104 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 return false;
5106}
5107
5108void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5109 mLock.unlock();
5110
5111 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5112
5113 mLock.lock();
5114}
5115
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005116KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5117 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005118 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005119 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5120 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005121 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122}
5123
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005124void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5125 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 // TODO Write some statistics about how long we spend waiting.
5127}
5128
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005129/**
5130 * Report the touch event latency to the statsd server.
5131 * Input events are reported for statistics if:
5132 * - This is a touchscreen event
5133 * - InputFilter is not enabled
5134 * - Event is not injected or synthesized
5135 *
5136 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5137 * from getting aggregated with the "old" data.
5138 */
5139void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5140 REQUIRES(mLock) {
5141 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5142 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5143 if (!reportForStatistics) {
5144 return;
5145 }
5146
5147 if (mTouchStatistics.shouldReport()) {
5148 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5149 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5150 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5151 mTouchStatistics.reset();
5152 }
5153 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5154 mTouchStatistics.addValue(latencyMicros);
5155}
5156
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157void InputDispatcher::traceInboundQueueLengthLocked() {
5158 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005159 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
5161}
5162
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005163void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 if (ATRACE_ENABLED()) {
5165 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005166 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005167 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
5169}
5170
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005171void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 if (ATRACE_ENABLED()) {
5173 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005174 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005175 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 }
5177}
5178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005180 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005182 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 dumpDispatchStateLocked(dump);
5184
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005185 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005186 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005187 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
5189}
5190
5191void InputDispatcher::monitor() {
5192 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005193 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005195 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196}
5197
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005198/**
5199 * Wake up the dispatcher and wait until it processes all events and commands.
5200 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5201 * this method can be safely called from any thread, as long as you've ensured that
5202 * the work you are interested in completing has already been queued.
5203 */
5204bool InputDispatcher::waitForIdle() {
5205 /**
5206 * Timeout should represent the longest possible time that a device might spend processing
5207 * events and commands.
5208 */
5209 constexpr std::chrono::duration TIMEOUT = 100ms;
5210 std::unique_lock lock(mLock);
5211 mLooper->wake();
5212 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5213 return result == std::cv_status::no_timeout;
5214}
5215
Vishnu Naire798b472020-07-23 13:52:21 -07005216/**
5217 * Sets focus to the window identified by the token. This must be called
5218 * after updating any input window handles.
5219 *
5220 * Params:
5221 * request.token - input channel token used to identify the window that should gain focus.
5222 * request.focusedToken - the token that the caller expects currently to be focused. If the
5223 * specified token does not match the currently focused window, this request will be dropped.
5224 * If the specified focused token matches the currently focused window, the call will succeed.
5225 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5226 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5227 * when requesting the focus change. This determines which request gets
5228 * precedence if there is a focus change request from another source such as pointer down.
5229 */
Vishnu Nair958da932020-08-21 17:12:37 -07005230void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5231 { // acquire lock
5232 std::scoped_lock _l(mLock);
5233
5234 const int32_t displayId = request.displayId;
5235 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5236 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5237 ALOGD_IF(DEBUG_FOCUS,
5238 "setFocusedWindow on display %" PRId32
5239 " ignored, reason: focusedToken is not focused",
5240 displayId);
5241 return;
5242 }
5243
5244 mPendingFocusRequests.erase(displayId);
5245 FocusResult result = handleFocusRequestLocked(request);
5246 if (result == FocusResult::NOT_VISIBLE) {
5247 // The requested window is not currently visible. Wait for the window to become visible
5248 // and then provide it focus. This is to handle situations where a user action triggers
5249 // a new window to appear. We want to be able to queue any key events after the user
5250 // action and deliver it to the newly focused window. In order for this to happen, we
5251 // take focus from the currently focused window so key events can be queued.
5252 ALOGD_IF(DEBUG_FOCUS,
5253 "setFocusedWindow on display %" PRId32
5254 " pending, reason: window is not visible",
5255 displayId);
5256 mPendingFocusRequests[displayId] = request;
5257 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5258 "setFocusedWindow_AwaitingWindowVisibility");
5259 } else if (result != FocusResult::OK) {
5260 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5261 typeToString(result));
5262 }
5263 } // release lock
5264 // Wake up poll loop since it may need to make new input dispatching choices.
5265 mLooper->wake();
5266}
5267
5268InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5269 const FocusRequest& request) {
5270 const int32_t displayId = request.displayId;
5271 const sp<IBinder> newFocusedToken = request.token;
5272 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5273
5274 if (oldFocusedToken == request.token) {
5275 ALOGD_IF(DEBUG_FOCUS,
5276 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5277 displayId);
5278 return FocusResult::OK;
5279 }
5280
5281 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5282 if (result != FocusResult::OK) {
5283 return result;
5284 }
5285
5286 std::string_view reason =
5287 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5288 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5289 return FocusResult::OK;
5290}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005291
Vishnu Nairad321cd2020-08-20 16:40:21 -07005292void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5293 const sp<IBinder>& newFocusedToken, int32_t displayId,
5294 std::string_view reason) {
5295 if (oldFocusedToken) {
5296 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005297 if (focusedInputChannel) {
5298 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5299 "focus left window");
5300 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005301 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005302 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005303 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005304 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005305 if (newFocusedToken) {
5306 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5307 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005308 }
5309
5310 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005311 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005312 }
5313}
Vishnu Nair958da932020-08-21 17:12:37 -07005314
5315/**
5316 * Checks if the window token can be focused on a display. The token can be focused if there is
5317 * at least one window handle that is visible with the same token and all window handles with the
5318 * same token are focusable.
5319 *
5320 * In the case of mirroring, two windows may share the same window token and their visibility
5321 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5322 * we expect the focusability of the windows to match since its hard to reason why one window can
5323 * receive focus events and the other cannot when both are backed by the same input channel.
5324 */
5325InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5326 int32_t displayId) const {
5327 bool allWindowsAreFocusable = true;
5328 bool visibleWindowFound = false;
5329 bool windowFound = false;
5330 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5331 if (window->getToken() != token) {
5332 continue;
5333 }
5334 windowFound = true;
5335 if (window->getInfo()->visible) {
5336 // Check if at least a single window is visible.
5337 visibleWindowFound = true;
5338 }
5339 if (!window->getInfo()->focusable) {
5340 // Check if all windows with the window token are focusable.
5341 allWindowsAreFocusable = false;
5342 break;
5343 }
5344 }
5345
5346 if (!windowFound) {
5347 return FocusResult::NO_WINDOW;
5348 }
5349 if (!allWindowsAreFocusable) {
5350 return FocusResult::NOT_FOCUSABLE;
5351 }
5352 if (!visibleWindowFound) {
5353 return FocusResult::NOT_VISIBLE;
5354 }
5355
5356 return FocusResult::OK;
5357}
Garfield Tane84e6f92019-08-29 17:28:41 -07005358} // namespace android::inputdispatcher