blob: 5dc399e36be197b07f207818f34596d6b14b8e95 [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),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100405 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800408 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
Yi Kong9b14ac62018-07-17 13:48:38 -0700410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 policy->getDispatcherConfiguration(&mConfig);
413}
414
415InputDispatcher::~InputDispatcher() {
416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700426 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 }
428}
429
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700431 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return ALREADY_EXISTS;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437}
438
439status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return INVALID_OPERATION;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread.reset();
445 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446}
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482}
483
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700484/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500485 * Raise ANR if there is no focused window.
486 * Before the ANR is raised, do a final state check:
487 * 1. The currently focused application must be the same one we are waiting for.
488 * 2. Ensure we still don't have a focused window.
489 */
490void InputDispatcher::processNoFocusedWindowAnrLocked() {
491 // Check if the application that we are waiting for is still focused.
492 std::shared_ptr<InputApplicationHandle> focusedApplication =
493 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
494 if (focusedApplication == nullptr ||
495 focusedApplication->getApplicationToken() !=
496 mAwaitedFocusedApplication->getApplicationToken()) {
497 // Unexpected because we should have reset the ANR timer when focused application changed
498 ALOGE("Waited for a focused window, but focused application has already changed to %s",
499 focusedApplication->getName().c_str());
500 return; // The focused application has changed.
501 }
502
503 const sp<InputWindowHandle>& focusedWindowHandle =
504 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
505 if (focusedWindowHandle != nullptr) {
506 return; // We now have a focused window. No need for ANR.
507 }
508 onAnrLocked(mAwaitedFocusedApplication);
509}
510
511/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700512 * Check if any of the connections' wait queues have events that are too old.
513 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
514 * Return the time at which we should wake up next.
515 */
516nsecs_t InputDispatcher::processAnrsLocked() {
517 const nsecs_t currentTime = now();
518 nsecs_t nextAnrCheck = LONG_LONG_MAX;
519 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
520 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
521 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500522 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700523 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500524 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700525 return LONG_LONG_MIN;
526 } else {
527 // Keep waiting
528 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
529 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
530 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
531 }
532 }
533
534 // Check if any connection ANRs are due
535 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
536 if (currentTime < nextAnrCheck) { // most likely scenario
537 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
538 }
539
540 // If we reached here, we have an unresponsive connection.
541 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
542 if (connection == nullptr) {
543 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
544 return nextAnrCheck;
545 }
546 connection->responsive = false;
547 // Stop waking up for this unresponsive connection
548 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500549 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700550 return LONG_LONG_MIN;
551}
552
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500553std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700554 sp<InputWindowHandle> window = getWindowHandleLocked(token);
555 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500556 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700557 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500558 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700559}
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
562 nsecs_t currentTime = now();
563
Jeff Browndc5992e2014-04-11 01:27:26 -0700564 // Reset the key repeat timer whenever normal dispatch is suspended while the
565 // device is in a non-interactive state. This is to ensure that we abort a key
566 // repeat if the device is just coming out of sleep.
567 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 resetKeyRepeatLocked();
569 }
570
571 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
572 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100573 if (DEBUG_FOCUS) {
574 ALOGD("Dispatch frozen. Waiting some more.");
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 return;
577 }
578
579 // Optimize latency of app switches.
580 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
581 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
582 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
583 if (mAppSwitchDueTime < *nextWakeupTime) {
584 *nextWakeupTime = mAppSwitchDueTime;
585 }
586
587 // Ready to start a new event.
588 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700590 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 if (isAppSwitchDue) {
592 // The inbound queue is empty so the app switch key we were waiting
593 // for will never arrive. Stop waiting for it.
594 resetPendingAppSwitchLocked(false);
595 isAppSwitchDue = false;
596 }
597
598 // Synthesize a key repeat if appropriate.
599 if (mKeyRepeatState.lastKeyEntry) {
600 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
601 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
602 } else {
603 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
604 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
605 }
606 }
607 }
608
609 // Nothing to do if there is no pending event.
610 if (!mPendingEvent) {
611 return;
612 }
613 } else {
614 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700615 mPendingEvent = mInboundQueue.front();
616 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 traceInboundQueueLengthLocked();
618 }
619
620 // Poke user activity for this event.
621 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700622 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625
626 // Now we have an event to dispatch.
627 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700628 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700632 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700634 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
636
637 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700638 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
640
641 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700642 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 ConfigurationChangedEntry* typedEntry =
644 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
645 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700646 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700647 break;
648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700650 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700651 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
652 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 break;
655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100657 case EventEntry::Type::FOCUS: {
658 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
659 dispatchFocusLocked(currentTime, typedEntry);
660 done = true;
661 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
662 break;
663 }
664
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700665 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
667 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700668 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 resetPendingAppSwitchLocked(true);
670 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700671 } else if (dropReason == DropReason::NOT_DROPPED) {
672 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 }
674 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700676 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
679 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 }
681 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
682 break;
683 }
684
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700685 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700686 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700687 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
688 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700690 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700691 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700693 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
694 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 }
696 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
700
701 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700702 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Michael Wright3a981722015-06-10 15:26:13 +0100705 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706
707 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 }
710}
711
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700712/**
713 * Return true if the events preceding this incoming motion event should be dropped
714 * Return false otherwise (the default behaviour)
715 */
716bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700718 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719
720 // Optimize case where the current application is unresponsive and the user
721 // decides to touch a window in a different application.
722 // If the application takes too long to catch up then we drop all events preceding
723 // the touch into the other window.
724 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700725 int32_t displayId = motionEntry.displayId;
726 int32_t x = static_cast<int32_t>(
727 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
728 int32_t y = static_cast<int32_t>(
729 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
730 sp<InputWindowHandle> touchedWindowHandle =
731 findTouchedWindowAtLocked(displayId, x, y, nullptr);
732 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700733 touchedWindowHandle->getApplicationToken() !=
734 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700735 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 ALOGI("Pruning input queue because user touched a different application while waiting "
737 "for %s",
738 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700739 return true;
740 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700741
742 // Alternatively, maybe there's a gesture monitor that could handle this event
743 std::vector<TouchedMonitor> gestureMonitors =
744 findTouchedGestureMonitorsLocked(displayId, {});
745 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
746 sp<Connection> connection =
747 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000748 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700749 // This monitor could take more input. Drop all events preceding this
750 // event, so that gesture monitor could get a chance to receive the stream
751 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
752 "responsive gesture monitor that may handle the event",
753 mAwaitedFocusedApplication->getName().c_str());
754 return true;
755 }
756 }
757 }
758
759 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
760 // yet been processed by some connections, the dispatcher will wait for these motion
761 // events to be processed before dispatching the key event. This is because these motion events
762 // may cause a new window to be launched, which the user might expect to receive focus.
763 // To prevent waiting forever for such events, just send the key to the currently focused window
764 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
765 ALOGD("Received a new pointer down event, stop waiting for events to process and "
766 "just send the pending key event to the focused window.");
767 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700768 }
769 return false;
770}
771
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700773 bool needWake = mInboundQueue.empty();
774 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 traceInboundQueueLengthLocked();
776
777 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700778 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 // Optimize app switch latency.
780 // If the application takes too long to catch up then we drop all events preceding
781 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700782 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700791 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 mAppSwitchSawKeyDown = false;
793 needWake = true;
794 }
795 }
796 }
797 break;
798 }
799
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700800 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700801 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
802 mNextUnblockedEvent = entry;
803 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100807 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700808 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
809 break;
810 }
811 case EventEntry::Type::CONFIGURATION_CHANGED:
812 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 // nothing to do
814 break;
815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 return needWake;
819}
820
821void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
822 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700823 mRecentQueue.push_back(entry);
824 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
825 mRecentQueue.front()->release();
826 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828}
829
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700831 int32_t y, TouchState* touchState,
832 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
835 LOG_ALWAYS_FATAL(
836 "Must provide a valid touch state if adding portal windows or outside targets");
837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700839 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800840 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 const InputWindowInfo* windowInfo = windowHandle->getInfo();
842 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100843 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844
845 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100846 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
847 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
848 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800850 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 if (portalToDisplayId != ADISPLAY_ID_NONE &&
852 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800853 if (addPortalWindows) {
854 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700855 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800856 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700857 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 // Found window.
861 return windowHandle;
862 }
863 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800864
Michael Wright44753b12020-07-08 13:48:11 +0100865 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700866 touchState->addOrUpdateWindow(windowHandle,
867 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
868 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 }
872 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700873 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874}
875
Garfield Tane84e6f92019-08-29 17:28:41 -0700876std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700877 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000878 std::vector<TouchedMonitor> touchedMonitors;
879
880 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
881 addGestureMonitors(monitors, touchedMonitors);
882 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
883 const InputWindowInfo* windowInfo = portalWindow->getInfo();
884 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
886 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000887 }
888 return touchedMonitors;
889}
890
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 const char* reason;
893 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 reason = "inbound event was dropped because the policy consumed it";
899 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 case DropReason::DISABLED:
901 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 ALOGI("Dropped event because input dispatch is disabled.");
903 }
904 reason = "inbound event was dropped because input dispatch is disabled";
905 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700906 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 ALOGI("Dropped event because of pending overdue app switch.");
908 reason = "inbound event was dropped because of pending overdue app switch";
909 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700910 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 ALOGI("Dropped event because the current application is not responding and the user "
912 "has started interacting with a different application.");
913 reason = "inbound event was dropped because the current application is not responding "
914 "and the user has started interacting with a different application";
915 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700916 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917 ALOGI("Dropped event because it is stale.");
918 reason = "inbound event was dropped because it is stale";
919 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700920 case DropReason::NOT_DROPPED: {
921 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700926 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700927 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
929 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700932 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700933 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
934 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
936 synthesizeCancelationEventsForAllConnectionsLocked(options);
937 } else {
938 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
939 synthesizeCancelationEventsForAllConnectionsLocked(options);
940 }
941 break;
942 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100943 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700944 case EventEntry::Type::CONFIGURATION_CHANGED:
945 case EventEntry::Type::DEVICE_RESET: {
946 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
947 break;
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
950}
951
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800952static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
954 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955}
956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
958 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
959 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
960 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961}
962
963bool InputDispatcher::isAppSwitchPendingLocked() {
964 return mAppSwitchDueTime != LONG_LONG_MAX;
965}
966
967void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
968 mAppSwitchDueTime = LONG_LONG_MAX;
969
970#if DEBUG_APP_SWITCH
971 if (handled) {
972 ALOGD("App switch has arrived.");
973 } else {
974 ALOGD("App switch was abandoned.");
975 }
976#endif
977}
978
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700980 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981}
982
983bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700984 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 return false;
986 }
987
988 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700989 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700992 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993
994 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700995 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 return true;
997}
998
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700999void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1000 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001}
1002
1003void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001004 while (!mInboundQueue.empty()) {
1005 EventEntry* entry = mInboundQueue.front();
1006 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 releaseInboundEventLocked(entry);
1008 }
1009 traceInboundQueueLengthLocked();
1010}
1011
1012void InputDispatcher::releasePendingEventLocked() {
1013 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017}
1018
1019void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1020 InjectionState* injectionState = entry->injectionState;
1021 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1022#if DEBUG_DISPATCH_CYCLE
1023 ALOGD("Injected inbound event was dropped.");
1024#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001025 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001028 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030 addRecentEventLocked(entry);
1031 entry->release();
1032}
1033
1034void InputDispatcher::resetKeyRepeatLocked() {
1035 if (mKeyRepeatState.lastKeyEntry) {
1036 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001037 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039}
1040
Garfield Tane84e6f92019-08-29 17:28:41 -07001041KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1043
1044 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001045 uint32_t policyFlags = entry->policyFlags &
1046 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 if (entry->refCount == 1) {
1048 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001049 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 entry->eventTime = currentTime;
1051 entry->policyFlags = policyFlags;
1052 entry->repeatCount += 1;
1053 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001055 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001056 entry->displayId, policyFlags, entry->action, entry->flags,
1057 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059
1060 mKeyRepeatState.lastKeyEntry = newEntry;
1061 entry->release();
1062
1063 entry = newEntry;
1064 }
1065 entry->syntheticRepeat = true;
1066
1067 // Increment reference count since we keep a reference to the event in
1068 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1069 entry->refCount += 1;
1070
1071 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1072 return entry;
1073}
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1076 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001078 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079#endif
1080
1081 // Reset key repeating in case a keyboard device was added or removed or something.
1082 resetKeyRepeatLocked();
1083
1084 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001085 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1086 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 return true;
1090}
1091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001094 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096#endif
1097
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 options.deviceId = entry->deviceId;
1100 synthesizeCancelationEventsForAllConnectionsLocked(options);
1101 return true;
1102}
1103
Vishnu Nairad321cd2020-08-20 16:40:21 -07001104void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001105 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001106 if (mPendingEvent != nullptr) {
1107 // Move the pending event to the front of the queue. This will give the chance
1108 // for the pending event to get dispatched to the newly focused window
1109 mInboundQueue.push_front(mPendingEvent);
1110 mPendingEvent = nullptr;
1111 }
1112
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001113 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001114 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001115
1116 // This event should go to the front of the queue, but behind all other focus events
1117 // Find the last focus event, and insert right after it
1118 std::deque<EventEntry*>::reverse_iterator it =
1119 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1120 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1121
1122 // Maintain the order of focus events. Insert the entry after all other focus events.
1123 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001124}
1125
1126void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001127 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001128 if (channel == nullptr) {
1129 return; // Window has gone away
1130 }
1131 InputTarget target;
1132 target.inputChannel = channel;
1133 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1134 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001135 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1136 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001137 std::string reason = std::string("reason=").append(entry->reason);
1138 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001139 dispatchEventLocked(currentTime, entry, {target});
1140}
1141
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 if (!entry->dispatchInProgress) {
1146 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1147 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1148 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1149 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001150 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 // We have seen two identical key downs in a row which indicates that the device
1152 // driver is automatically generating key repeats itself. We take note of the
1153 // repeat here, but we disable our own next key repeat timer since it is clear that
1154 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001155 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1156 // Make sure we don't get key down from a different device. If a different
1157 // device Id has same key pressed down, the new device Id will replace the
1158 // current one to hold the key repeat with repeat count reset.
1159 // In the future when got a KEY_UP on the device id, drop it and do not
1160 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1162 resetKeyRepeatLocked();
1163 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1164 } else {
1165 // Not a repeat. Save key down state in case we do see a repeat later.
1166 resetKeyRepeatLocked();
1167 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1168 }
1169 mKeyRepeatState.lastKeyEntry = entry;
1170 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001171 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1172 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1173 // The stale device releases the key, reset staleDeviceId.
1174#if DEBUG_INBOUND_EVENT_DETAILS
1175 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1176#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 resetKeyRepeatLocked();
1179 }
1180
1181 if (entry->repeatCount == 1) {
1182 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1183 } else {
1184 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1185 }
1186
1187 entry->dispatchInProgress = true;
1188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001189 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191
1192 // Handle case where the policy asked us to try again later last time.
1193 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1194 if (currentTime < entry->interceptKeyWakeupTime) {
1195 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1196 *nextWakeupTime = entry->interceptKeyWakeupTime;
1197 }
1198 return false; // wait until next wakeup
1199 }
1200 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1201 entry->interceptKeyWakeupTime = 0;
1202 }
1203
1204 // Give the policy a chance to intercept the key.
1205 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1206 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001207 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001208 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001209 sp<IBinder> focusedWindowToken =
1210 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1211 if (focusedWindowToken != nullptr) {
1212 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 entry->refCount += 1;
1217 return false; // wait for the command to run
1218 } else {
1219 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1220 }
1221 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001222 if (*dropReason == DropReason::NOT_DROPPED) {
1223 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225 }
1226
1227 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001230 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001232 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 return true;
1234 }
1235
1236 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001237 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1241 return false;
1242 }
1243
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001244 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1246 return true;
1247 }
1248
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001249 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001250 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 // Dispatch the key.
1253 dispatchEventLocked(currentTime, entry, inputTargets);
1254 return true;
1255}
1256
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001259 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1261 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1263 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1264 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#endif
1266}
1267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1269 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001270 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 entry->dispatchInProgress = true;
1274
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001275 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277
1278 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001279 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001281 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 return true;
1284 }
1285
1286 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1287
1288 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001289 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
1291 bool conflictingPointerActions = false;
1292 int32_t injectionResult;
1293 if (isPointerEvent) {
1294 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001296 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 } else {
1299 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001301 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
1303 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1304 return false;
1305 }
1306
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001307 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001308 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1309 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1310 return true;
1311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001313 CancelationOptions::Mode mode(isPointerEvent
1314 ? CancelationOptions::CANCEL_POINTER_EVENTS
1315 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1316 CancelationOptions options(mode, "input event injection failed");
1317 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 return true;
1319 }
1320
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001321 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001324 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001325 std::unordered_map<int32_t, TouchState>::iterator it =
1326 mTouchStatesByDisplay.find(entry->displayId);
1327 if (it != mTouchStatesByDisplay.end()) {
1328 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001329 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001330 // The event has gone through these portal windows, so we add monitoring targets of
1331 // the corresponding displays as well.
1332 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001333 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001334 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001336 }
1337 }
1338 }
1339 }
1340
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Dispatch the motion.
1342 if (conflictingPointerActions) {
1343 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001344 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 synthesizeCancelationEventsForAllConnectionsLocked(options);
1346 }
1347 dispatchEventLocked(currentTime, entry, inputTargets);
1348 return true;
1349}
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001353 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 ", policyFlags=0x%x, "
1355 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1356 "metaState=0x%x, buttonState=0x%x,"
1357 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001358 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1359 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1360 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 "x=%f, y=%f, pressure=%f, size=%f, "
1365 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1366 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001367 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1368 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1369 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1370 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1371 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1372 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1373 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1374 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1375 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1376 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378#endif
1379}
1380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1382 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001383 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384#if DEBUG_DISPATCH_CYCLE
1385 ALOGD("dispatchEventToCurrentInputTargets");
1386#endif
1387
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001388 updateInteractionTokensLocked(*eventEntry, inputTargets);
1389
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001394 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001395 sp<Connection> connection =
1396 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001397 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001398 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001400 if (DEBUG_FOCUS) {
1401 ALOGD("Dropping event delivery to target with channel '%s' because it "
1402 "is no longer registered with the input dispatcher.",
1403 inputTarget.inputChannel->getName().c_str());
1404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 }
1406 }
1407}
1408
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001409void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1410 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1411 // If the policy decides to close the app, we will get a channel removal event via
1412 // unregisterInputChannel, and will clean up the connection that way. We are already not
1413 // sending new pointers to the connection when it blocked, but focused events will continue to
1414 // pile up.
1415 ALOGW("Canceling events for %s because it is unresponsive",
1416 connection->inputChannel->getName().c_str());
1417 if (connection->status == Connection::STATUS_NORMAL) {
1418 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1419 "application not responding");
1420 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 }
1422}
1423
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001424void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001425 if (DEBUG_FOCUS) {
1426 ALOGD("Resetting ANR timeouts.");
1427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428
1429 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001430 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001431 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432}
1433
Tiger Huang721e26f2018-07-24 22:26:19 +08001434/**
1435 * Get the display id that the given event should go to. If this event specifies a valid display id,
1436 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1437 * Focused display is the display that the user most recently interacted with.
1438 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001440 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001441 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001442 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1444 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 break;
1446 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001447 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1449 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 break;
1451 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001453 case EventEntry::Type::CONFIGURATION_CHANGED:
1454 case EventEntry::Type::DEVICE_RESET: {
1455 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 return ADISPLAY_ID_NONE;
1457 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001458 }
1459 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1460}
1461
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001462bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1463 const char* focusedWindowName) {
1464 if (mAnrTracker.empty()) {
1465 // already processed all events that we waited for
1466 mKeyIsWaitingForEventsTimeout = std::nullopt;
1467 return false;
1468 }
1469
1470 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1471 // Start the timer
1472 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1473 "focus to change",
1474 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001475 mKeyIsWaitingForEventsTimeout = currentTime +
1476 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1477 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001478 return true;
1479 }
1480
1481 // We still have pending events, and already started the timer
1482 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1483 return true; // Still waiting
1484 }
1485
1486 // Waited too long, and some connection still hasn't processed all motions
1487 // Just send the key to the focused window
1488 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1489 focusedWindowName);
1490 mKeyIsWaitingForEventsTimeout = std::nullopt;
1491 return false;
1492}
1493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001495 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 std::vector<InputTarget>& inputTargets,
1497 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001498 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499
Tiger Huang721e26f2018-07-24 22:26:19 +08001500 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001501 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001502 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001503 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1504
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 // If there is no currently focused window and no focused application
1506 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001507 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1508 ALOGI("Dropping %s event because there is no focused window or focused application in "
1509 "display %" PRId32 ".",
1510 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001511 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001514 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1515 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1516 // start interacting with another application via touch (app switch). This code can be removed
1517 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1518 // an app is expected to have a focused window.
1519 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1520 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1521 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001522 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1523 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1524 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001525 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001526 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001527 ALOGW("Waiting because no window has focus but %s may eventually add a "
1528 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001529 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001530 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1531 return INPUT_EVENT_INJECTION_PENDING;
1532 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1533 // Already raised ANR. Drop the event
1534 ALOGE("Dropping %s event because there is no focused window",
1535 EventEntry::typeToString(entry.type));
1536 return INPUT_EVENT_INJECTION_FAILED;
1537 } else {
1538 // Still waiting for the focused window
1539 return INPUT_EVENT_INJECTION_PENDING;
1540 }
1541 }
1542
1543 // we have a valid, non-null focused window
1544 resetNoFocusedWindowTimeoutLocked();
1545
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001548 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001551 if (focusedWindowHandle->getInfo()->paused) {
1552 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1553 return INPUT_EVENT_INJECTION_PENDING;
1554 }
1555
1556 // If the event is a key event, then we must wait for all previous events to
1557 // complete before delivering it because previous events may have the
1558 // side-effect of transferring focus to a different window and we want to
1559 // ensure that the following keys are sent to the new window.
1560 //
1561 // Suppose the user touches a button in a window then immediately presses "A".
1562 // If the button causes a pop-up window to appear then we want to ensure that
1563 // the "A" key is delivered to the new pop-up window. This is because users
1564 // often anticipate pending UI changes when typing on a keyboard.
1565 // To obtain this behavior, we must serialize key events with respect to all
1566 // prior input events.
1567 if (entry.type == EventEntry::Type::KEY) {
1568 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1569 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1570 return INPUT_EVENT_INJECTION_PENDING;
1571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573
1574 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001575 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1577 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578
1579 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001580 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581}
1582
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001583/**
1584 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1585 * that are currently unresponsive.
1586 */
1587std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1588 const std::vector<TouchedMonitor>& monitors) const {
1589 std::vector<TouchedMonitor> responsiveMonitors;
1590 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1591 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1592 sp<Connection> connection = getConnectionLocked(
1593 monitor.monitor.inputChannel->getConnectionToken());
1594 if (connection == nullptr) {
1595 ALOGE("Could not find connection for monitor %s",
1596 monitor.monitor.inputChannel->getName().c_str());
1597 return false;
1598 }
1599 if (!connection->responsive) {
1600 ALOGW("Unresponsive monitor %s will not get the new gesture",
1601 connection->inputChannel->getName().c_str());
1602 return false;
1603 }
1604 return true;
1605 });
1606 return responsiveMonitors;
1607}
1608
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 std::vector<InputTarget>& inputTargets,
1612 nsecs_t* nextWakeupTime,
1613 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 enum InjectionPermission {
1616 INJECTION_PERMISSION_UNKNOWN,
1617 INJECTION_PERMISSION_GRANTED,
1618 INJECTION_PERMISSION_DENIED
1619 };
1620
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 // For security reasons, we defer updating the touch state until we are sure that
1622 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 int32_t displayId = entry.displayId;
1624 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1626
1627 // Update the touch state as needed based on the properties of the touch event.
1628 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1629 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001630 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1631 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001633 // Copy current touch state into tempTouchState.
1634 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1635 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001636 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001637 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001638 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1639 mTouchStatesByDisplay.find(displayId);
1640 if (oldStateIt != mTouchStatesByDisplay.end()) {
1641 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001642 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001643 }
1644
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001645 bool isSplit = tempTouchState.split;
1646 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1647 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1648 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1650 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1651 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1652 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1653 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 bool wrongDevice = false;
1656 if (newGesture) {
1657 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001658 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001659 ALOGI("Dropping event because a pointer for a different device is already down "
1660 "in display %" PRId32,
1661 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001662 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1664 switchedDevice = false;
1665 wrongDevice = true;
1666 goto Failed;
1667 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001668 tempTouchState.reset();
1669 tempTouchState.down = down;
1670 tempTouchState.deviceId = entry.deviceId;
1671 tempTouchState.source = entry.source;
1672 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001674 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001675 ALOGI("Dropping move event because a pointer for a different device is already active "
1676 "in display %" PRId32,
1677 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001678 // TODO: test multiple simultaneous input streams.
1679 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1680 switchedDevice = false;
1681 wrongDevice = true;
1682 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1686 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1687
Garfield Tan00f511d2019-06-12 16:55:40 -07001688 int32_t x;
1689 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001691 // Always dispatch mouse events to cursor position.
1692 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 x = int32_t(entry.xCursorPosition);
1694 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001695 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1697 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001698 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001699 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001700 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001701 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1702 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001703
1704 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001705 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 if (newTouchedWindowHandle != nullptr &&
1710 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001711 // New window supports splitting, but we should never split mouse events.
1712 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 } else if (isSplit) {
1714 // New window does not support splitting but we have already split events.
1715 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718
1719 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001722 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 }
1724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1726 ALOGI("Not sending touch event to %s because it is paused",
1727 newTouchedWindowHandle->getName().c_str());
1728 newTouchedWindowHandle = nullptr;
1729 }
1730
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001731 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001733 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1734 if (!isResponsive) {
1735 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1737 newTouchedWindowHandle = nullptr;
1738 }
1739 }
1740
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001741 // Drop events that can't be trusted due to occlusion
1742 if (newTouchedWindowHandle != nullptr &&
1743 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1744 TouchOcclusionInfo occlusionInfo =
1745 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001746 if (!isTouchTrustedLocked(occlusionInfo)) {
1747 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1748 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1749 ALOGW("Dropping untrusted touch event due to %s/%d",
1750 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1751 newTouchedWindowHandle = nullptr;
1752 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001753 }
1754 }
1755
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001756 // Also don't send the new touch event to unresponsive gesture monitors
1757 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1758
Michael Wright3dd60e22019-03-27 22:06:44 +00001759 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1760 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001761 "(%d, %d) in display %" PRId32 ".",
1762 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001763 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1764 goto Failed;
1765 }
1766
1767 if (newTouchedWindowHandle != nullptr) {
1768 // Set target flags.
1769 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1770 if (isSplit) {
1771 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001773 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1774 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1775 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1776 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1777 }
1778
1779 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001780 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1781 newHoverWindowHandle = nullptr;
1782 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001783 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001784 }
1785
1786 // Update the temporary touch state.
1787 BitSet32 pointerIds;
1788 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001790 pointerIds.markBit(pointerId);
1791 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001792 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001795 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 } else {
1797 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1798
1799 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001800 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001801 if (DEBUG_FOCUS) {
1802 ALOGD("Dropping event because the pointer is not down or we previously "
1803 "dropped the pointer down event in display %" PRId32,
1804 displayId);
1805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1807 goto Failed;
1808 }
1809
1810 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001811 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001812 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001813 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1814 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
1816 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001817 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001818 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1820 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001821 if (DEBUG_FOCUS) {
1822 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1823 oldTouchedWindowHandle->getName().c_str(),
1824 newTouchedWindowHandle->getName().c_str(), displayId);
1825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001827 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1828 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1829 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830
1831 // Make a slippery entrance into the new window.
1832 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1833 isSplit = true;
1834 }
1835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001836 int32_t targetFlags =
1837 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 if (isSplit) {
1839 targetFlags |= InputTarget::FLAG_SPLIT;
1840 }
1841 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1842 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1843 }
1844
1845 BitSet32 pointerIds;
1846 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001847 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001849 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 }
1851 }
1852 }
1853
1854 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001855 // Let the previous window know that the hover sequence is over, unless we already did it
1856 // when dispatching it as is to newTouchedWindowHandle.
1857 if (mLastHoverWindowHandle != nullptr &&
1858 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1859 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860#if DEBUG_HOVER
1861 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001862 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001864 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1865 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 }
1867
Garfield Tandf26e862020-07-01 20:18:19 -07001868 // Let the new window know that the hover sequence is starting, unless we already did it
1869 // when dispatching it as is to newTouchedWindowHandle.
1870 if (newHoverWindowHandle != nullptr &&
1871 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1872 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873#if DEBUG_HOVER
1874 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001875 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001877 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1878 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1879 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
1881 }
1882
1883 // Check permission to inject into all touched foreground windows and ensure there
1884 // is at least one touched foreground window.
1885 {
1886 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001887 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1889 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001890 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1892 injectionPermission = INJECTION_PERMISSION_DENIED;
1893 goto Failed;
1894 }
1895 }
1896 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001897 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001898 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001899 ALOGI("Dropping event because there is no touched foreground window in display "
1900 "%" PRId32 " or gesture monitor to receive it.",
1901 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1903 goto Failed;
1904 }
1905
1906 // Permission granted to injection into all touched foreground windows.
1907 injectionPermission = INJECTION_PERMISSION_GRANTED;
1908 }
1909
1910 // Check whether windows listening for outside touches are owned by the same UID. If it is
1911 // set the policy flag that we will not reveal coordinate information to this window.
1912 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1913 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001914 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 if (foregroundWindowHandle) {
1916 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001918 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1919 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1920 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001921 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1922 InputTarget::FLAG_ZERO_COORDS,
1923 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926 }
1927 }
1928 }
1929
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 // If this is the first pointer going down and the touched window has a wallpaper
1931 // then also add the touched wallpaper windows so they are locked in for the duration
1932 // of the touch gesture.
1933 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1934 // engine only supports touch events. We would need to add a mechanism similar
1935 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1936 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1937 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001938 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001939 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001940 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001941 getWindowHandlesLocked(displayId);
1942 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001944 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001945 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001946 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947 .addOrUpdateWindow(windowHandle,
1948 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1949 InputTarget::
1950 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1951 InputTarget::FLAG_DISPATCH_AS_IS,
1952 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
1954 }
1955 }
1956 }
1957
1958 // Success! Output targets.
1959 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1960
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001961 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001963 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001966 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001968 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 }
1970
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 // Drop the outside or hover touch windows since we will not care about them
1972 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001973 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974
1975Failed:
1976 // Check injection permission once and for all.
1977 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001978 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 injectionPermission = INJECTION_PERMISSION_GRANTED;
1980 } else {
1981 injectionPermission = INJECTION_PERMISSION_DENIED;
1982 }
1983 }
1984
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001985 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1986 return injectionResult;
1987 }
1988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 if (!wrongDevice) {
1991 if (switchedDevice) {
1992 if (DEBUG_FOCUS) {
1993 ALOGD("Conflicting pointer actions: Switched to a different device.");
1994 }
1995 *outConflictingPointerActions = true;
1996 }
1997
1998 if (isHoverAction) {
1999 // Started hovering, therefore no longer down.
2000 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002001 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002002 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2003 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 *outConflictingPointerActions = true;
2006 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002007 tempTouchState.reset();
2008 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2009 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2010 tempTouchState.deviceId = entry.deviceId;
2011 tempTouchState.source = entry.source;
2012 tempTouchState.displayId = displayId;
2013 }
2014 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2015 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2016 // All pointers up or canceled.
2017 tempTouchState.reset();
2018 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2019 // First pointer went down.
2020 if (oldState && oldState->down) {
2021 if (DEBUG_FOCUS) {
2022 ALOGD("Conflicting pointer actions: Down received while already down.");
2023 }
2024 *outConflictingPointerActions = true;
2025 }
2026 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2027 // One pointer went up.
2028 if (isSplit) {
2029 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2030 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002032 for (size_t i = 0; i < tempTouchState.windows.size();) {
2033 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2034 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2035 touchedWindow.pointerIds.clearBit(pointerId);
2036 if (touchedWindow.pointerIds.isEmpty()) {
2037 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2038 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002041 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002043 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002044 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002045
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002046 // Save changes unless the action was scroll in which case the temporary touch
2047 // state was only valid for this one action.
2048 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2049 if (tempTouchState.displayId >= 0) {
2050 mTouchStatesByDisplay[displayId] = tempTouchState;
2051 } else {
2052 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002056 // Update hover state.
2057 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
2059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 return injectionResult;
2061}
2062
2063void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 int32_t targetFlags, BitSet32 pointerIds,
2065 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002066 std::vector<InputTarget>::iterator it =
2067 std::find_if(inputTargets.begin(), inputTargets.end(),
2068 [&windowHandle](const InputTarget& inputTarget) {
2069 return inputTarget.inputChannel->getConnectionToken() ==
2070 windowHandle->getToken();
2071 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002072
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002073 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002074
2075 if (it == inputTargets.end()) {
2076 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002077 std::shared_ptr<InputChannel> inputChannel =
2078 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002079 if (inputChannel == nullptr) {
2080 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2081 return;
2082 }
2083 inputTarget.inputChannel = inputChannel;
2084 inputTarget.flags = targetFlags;
2085 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2086 inputTargets.push_back(inputTarget);
2087 it = inputTargets.end() - 1;
2088 }
2089
2090 ALOG_ASSERT(it->flags == targetFlags);
2091 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2092
chaviw1ff3d1e2020-07-01 15:53:47 -07002093 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094}
2095
Michael Wright3dd60e22019-03-27 22:06:44 +00002096void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002097 int32_t displayId, float xOffset,
2098 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002099 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2100 mGlobalMonitorsByDisplay.find(displayId);
2101
2102 if (it != mGlobalMonitorsByDisplay.end()) {
2103 const std::vector<Monitor>& monitors = it->second;
2104 for (const Monitor& monitor : monitors) {
2105 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 }
2108}
2109
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002110void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2111 float yOffset,
2112 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 InputTarget target;
2114 target.inputChannel = monitor.inputChannel;
2115 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002116 ui::Transform t;
2117 t.set(xOffset, yOffset);
2118 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 inputTargets.push_back(target);
2120}
2121
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 const InjectionState* injectionState) {
2124 if (injectionState &&
2125 (windowHandle == nullptr ||
2126 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2127 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002128 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002130 "owned by uid %d",
2131 injectionState->injectorPid, injectionState->injectorUid,
2132 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 } else {
2134 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002135 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137 return false;
2138 }
2139 return true;
2140}
2141
Robert Carrc9bf1d32020-04-13 17:21:08 -07002142/**
2143 * Indicate whether one window handle should be considered as obscuring
2144 * another window handle. We only check a few preconditions. Actually
2145 * checking the bounds is left to the caller.
2146 */
2147static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2148 const sp<InputWindowHandle>& otherHandle) {
2149 // Compare by token so cloned layers aren't counted
2150 if (haveSameToken(windowHandle, otherHandle)) {
2151 return false;
2152 }
2153 auto info = windowHandle->getInfo();
2154 auto otherInfo = otherHandle->getInfo();
2155 if (!otherInfo->visible) {
2156 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002157 } else if (info->ownerUid == otherInfo->ownerUid) {
2158 // If ownerUid is the same we don't generate occlusion events as there
2159 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002160 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002161 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002162 return false;
2163 } else if (otherInfo->displayId != info->displayId) {
2164 return false;
2165 }
2166 return true;
2167}
2168
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002169/**
2170 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2171 * untrusted, one should check:
2172 *
2173 * 1. If result.hasBlockingOcclusion is true.
2174 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2175 * BLOCK_UNTRUSTED.
2176 *
2177 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2178 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2179 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2180 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2181 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2182 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2183 *
2184 * If neither of those is true, then it means the touch can be allowed.
2185 */
2186InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2187 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2188 int32_t displayId = windowHandle->getInfo()->displayId;
2189 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2190 TouchOcclusionInfo info;
2191 info.hasBlockingOcclusion = false;
2192 info.obscuringOpacity = 0;
2193 info.obscuringUid = -1;
2194 std::map<int32_t, float> opacityByUid;
2195 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2196 if (windowHandle == otherHandle) {
2197 break; // All future windows are below us. Exit early.
2198 }
2199 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2200 if (canBeObscuredBy(windowHandle, otherHandle) &&
2201 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2202 otherInfo->frameContainsPoint(x, y)) {
2203 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2204 // we perform the checks below to see if the touch can be propagated or not based on the
2205 // window's touch occlusion mode
2206 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2207 info.hasBlockingOcclusion = true;
2208 info.obscuringUid = otherInfo->ownerUid;
2209 info.obscuringPackage = otherInfo->packageName;
2210 break;
2211 }
2212 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2213 uint32_t uid = otherInfo->ownerUid;
2214 float opacity =
2215 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2216 // Given windows A and B:
2217 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2218 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2219 opacityByUid[uid] = opacity;
2220 if (opacity > info.obscuringOpacity) {
2221 info.obscuringOpacity = opacity;
2222 info.obscuringUid = uid;
2223 info.obscuringPackage = otherInfo->packageName;
2224 }
2225 }
2226 }
2227 }
2228 return info;
2229}
2230
2231bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2232 if (occlusionInfo.hasBlockingOcclusion) {
2233 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2234 occlusionInfo.obscuringUid);
2235 return false;
2236 }
2237 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2238 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2239 "%.2f, maximum allowed = %.2f)",
2240 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2241 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2242 return false;
2243 }
2244 return true;
2245}
2246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002247bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2248 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002250 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002251 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002252 if (windowHandle == otherHandle) {
2253 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002256 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002257 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 return true;
2259 }
2260 }
2261 return false;
2262}
2263
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002264bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2265 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002266 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002267 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002268 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002269 if (windowHandle == otherHandle) {
2270 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002271 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002272 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002273 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002274 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002275 return true;
2276 }
2277 }
2278 return false;
2279}
2280
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002281std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002282 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002284 if (applicationHandle != nullptr) {
2285 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002286 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 } else {
2288 return applicationHandle->getName();
2289 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002290 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002291 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002293 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295}
2296
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002297void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002298 if (eventEntry.type == EventEntry::Type::FOCUS) {
2299 // Focus events are passed to apps, but do not represent user activity.
2300 return;
2301 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002302 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002303 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002304 if (focusedWindowHandle != nullptr) {
2305 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002306 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002308 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309#endif
2310 return;
2311 }
2312 }
2313
2314 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002315 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002316 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002317 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2318 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 return;
2320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002322 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002323 eventType = USER_ACTIVITY_EVENT_TOUCH;
2324 }
2325 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002327 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2329 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 return;
2331 }
2332 eventType = USER_ACTIVITY_EVENT_BUTTON;
2333 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002335 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002336 case EventEntry::Type::CONFIGURATION_CHANGED:
2337 case EventEntry::Type::DEVICE_RESET: {
2338 LOG_ALWAYS_FATAL("%s events are not user activity",
2339 EventEntry::typeToString(eventEntry.type));
2340 break;
2341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
2343
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002344 std::unique_ptr<CommandEntry> commandEntry =
2345 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002346 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002348 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349}
2350
2351void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 const sp<Connection>& connection,
2353 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002354 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002355 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002356 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002357 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002358 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002359 ATRACE_NAME(message.c_str());
2360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361#if DEBUG_DISPATCH_CYCLE
2362 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002363 "globalScaleFactor=%f, pointerIds=0x%x %s",
2364 connection->getInputChannelName().c_str(), inputTarget.flags,
2365 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2366 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367#endif
2368
2369 // Skip this event if the connection status is not normal.
2370 // We don't want to enqueue additional outbound events if the connection is broken.
2371 if (connection->status != Connection::STATUS_NORMAL) {
2372#if DEBUG_DISPATCH_CYCLE
2373 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375#endif
2376 return;
2377 }
2378
2379 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002380 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2381 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2382 "Entry type %s should not have FLAG_SPLIT",
2383 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002385 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002386 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002388 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 if (!splitMotionEntry) {
2390 return; // split event was dropped
2391 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002392 if (DEBUG_FOCUS) {
2393 ALOGD("channel '%s' ~ Split motion event.",
2394 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002395 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002396 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 splitMotionEntry->release();
2399 return;
2400 }
2401 }
2402
2403 // Not splitting. Enqueue dispatch entries for the event as is.
2404 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2405}
2406
2407void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002408 const sp<Connection>& connection,
2409 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002410 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002411 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002412 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002413 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002414 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002415 ATRACE_NAME(message.c_str());
2416 }
2417
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002418 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
2420 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002421 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002422 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002423 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002424 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002425 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002426 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002427 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002429 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002431 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433
2434 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002435 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 startDispatchCycleLocked(currentTime, connection);
2437 }
2438}
2439
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002440void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2441 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002442 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002443 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002444 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002445 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2446 connection->getInputChannelName().c_str(),
2447 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002448 ATRACE_NAME(message.c_str());
2449 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002450 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 if (!(inputTargetFlags & dispatchMode)) {
2452 return;
2453 }
2454 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2455
2456 // This is a new event.
2457 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002458 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002459 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002461 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2462 // different EventEntry than what was passed in.
2463 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002465 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002466 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002467 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002468 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002469 dispatchEntry->resolvedAction = keyEntry.action;
2470 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002472 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2473 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2476 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 return; // skip the inconsistent event
2479 }
2480 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002483 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002484 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002485 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2486 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2487 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2488 static_cast<int32_t>(IdGenerator::Source::OTHER);
2489 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2491 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2492 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2493 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2494 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2495 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2496 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2497 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2498 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2499 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2500 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002501 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002502 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 }
2504 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002505 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2506 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2509 "event",
2510 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002515 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2517 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2518 }
2519 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2520 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2524 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002526 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2527 "event",
2528 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530 return; // skip the inconsistent event
2531 }
2532
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002533 dispatchEntry->resolvedEventId =
2534 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2535 ? mIdGenerator.nextId()
2536 : motionEntry.id;
2537 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2538 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2539 ") to MotionEvent(id=0x%" PRIx32 ").",
2540 motionEntry.id, dispatchEntry->resolvedEventId);
2541 ATRACE_NAME(message.c_str());
2542 }
2543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002544 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002545 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546
2547 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002549 case EventEntry::Type::FOCUS: {
2550 break;
2551 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002552 case EventEntry::Type::CONFIGURATION_CHANGED:
2553 case EventEntry::Type::DEVICE_RESET: {
2554 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002555 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002556 break;
2557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
2560 // Remember that we are waiting for this dispatch to complete.
2561 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002562 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564
2565 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002566 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002567 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002568}
2569
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002570/**
2571 * This function is purely for debugging. It helps us understand where the user interaction
2572 * was taking place. For example, if user is touching launcher, we will see a log that user
2573 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2574 * We will see both launcher and wallpaper in that list.
2575 * Once the interaction with a particular set of connections starts, no new logs will be printed
2576 * until the set of interacted connections changes.
2577 *
2578 * The following items are skipped, to reduce the logspam:
2579 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2580 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2581 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2582 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2583 * Both of those ACTION_UP events would not be logged
2584 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2585 * will not be logged. This is omitted to reduce the amount of data printed.
2586 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2587 * gesture monitor is the only connection receiving the remainder of the gesture.
2588 */
2589void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2590 const std::vector<InputTarget>& targets) {
2591 // Skip ACTION_UP events, and all events other than keys and motions
2592 if (entry.type == EventEntry::Type::KEY) {
2593 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2594 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2595 return;
2596 }
2597 } else if (entry.type == EventEntry::Type::MOTION) {
2598 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2599 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2600 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2601 return;
2602 }
2603 } else {
2604 return; // Not a key or a motion
2605 }
2606
2607 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2608 std::vector<sp<Connection>> newConnections;
2609 for (const InputTarget& target : targets) {
2610 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2611 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2612 continue; // Skip windows that receive ACTION_OUTSIDE
2613 }
2614
2615 sp<IBinder> token = target.inputChannel->getConnectionToken();
2616 sp<Connection> connection = getConnectionLocked(token);
2617 if (connection == nullptr || connection->monitor) {
2618 continue; // We only need to keep track of the non-monitor connections.
2619 }
2620 newConnectionTokens.insert(std::move(token));
2621 newConnections.emplace_back(connection);
2622 }
2623 if (newConnectionTokens == mInteractionConnectionTokens) {
2624 return; // no change
2625 }
2626 mInteractionConnectionTokens = newConnectionTokens;
2627
2628 std::string windowList;
2629 for (const sp<Connection>& connection : newConnections) {
2630 windowList += connection->getWindowName() + ", ";
2631 }
2632 std::string message = "Interaction with windows: " + windowList;
2633 if (windowList.empty()) {
2634 message += "<none>";
2635 }
2636 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2637}
2638
chaviwfd6d3512019-03-25 13:23:49 -07002639void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002640 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002641 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002642 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2643 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002644 return;
2645 }
2646
Vishnu Nairad321cd2020-08-20 16:40:21 -07002647 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2648 if (focusedToken == token) {
2649 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002650 return;
2651 }
2652
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002653 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2654 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002655 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002656 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657}
2658
2659void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002661 if (ATRACE_ENABLED()) {
2662 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002664 ATRACE_NAME(message.c_str());
2665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002667 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668#endif
2669
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002670 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2671 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002673 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002674 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002675 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676
2677 // Publish the event.
2678 status_t status;
2679 EventEntry* eventEntry = dispatchEntry->eventEntry;
2680 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002681 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002682 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2683 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002686 status =
2687 connection->inputPublisher
2688 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2689 keyEntry->deviceId, keyEntry->source,
2690 keyEntry->displayId, std::move(hmac),
2691 dispatchEntry->resolvedAction,
2692 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2693 keyEntry->scanCode, keyEntry->metaState,
2694 keyEntry->repeatCount, keyEntry->downTime,
2695 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 }
2698
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002699 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002700 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 PointerCoords scaledCoords[MAX_POINTERS];
2703 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2704
chaviw82357092020-01-28 13:13:06 -08002705 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002706 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2707 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2708 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002709 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002710 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2711 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002712 // Don't apply window scale here since we don't want scale to affect raw
2713 // coordinates. The scale will be sent back to the client and applied
2714 // later when requesting relative coordinates.
2715 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2716 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 }
2718 usingCoords = scaledCoords;
2719 }
2720 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 // We don't want the dispatch target to know.
2722 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2723 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2724 scaledCoords[i].clear();
2725 }
2726 usingCoords = scaledCoords;
2727 }
2728 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002729
2730 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731
2732 // Publish the motion event.
2733 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002734 .publishMotionEvent(dispatchEntry->seq,
2735 dispatchEntry->resolvedEventId,
2736 motionEntry->deviceId, motionEntry->source,
2737 motionEntry->displayId, std::move(hmac),
2738 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 motionEntry->actionButton,
2740 dispatchEntry->resolvedFlags,
2741 motionEntry->edgeFlags, motionEntry->metaState,
2742 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002743 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002744 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002745 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 motionEntry->yPrecision,
2747 motionEntry->xCursorPosition,
2748 motionEntry->yCursorPosition,
2749 motionEntry->downTime, motionEntry->eventTime,
2750 motionEntry->pointerCount,
2751 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002752 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 break;
2754 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002755 case EventEntry::Type::FOCUS: {
2756 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2757 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002758 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002759 focusEntry->hasFocus,
2760 mInTouchMode);
2761 break;
2762 }
2763
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002764 case EventEntry::Type::CONFIGURATION_CHANGED:
2765 case EventEntry::Type::DEVICE_RESET: {
2766 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2767 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 }
2771
2772 // Check the result.
2773 if (status) {
2774 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002775 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 "This is unexpected because the wait queue is empty, so the pipe "
2778 "should be empty and we shouldn't have any problems writing an "
2779 "event to it, status=%d",
2780 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2782 } else {
2783 // Pipe is full and we are waiting for the app to finish process some events
2784 // before sending more events to it.
2785#if DEBUG_DISPATCH_CYCLE
2786 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 "waiting for the application to catch up",
2788 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
2791 } else {
2792 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 "status=%d",
2794 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2796 }
2797 return;
2798 }
2799
2800 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002801 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2802 connection->outboundQueue.end(),
2803 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002804 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002805 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002806 if (connection->responsive) {
2807 mAnrTracker.insert(dispatchEntry->timeoutTime,
2808 connection->inputChannel->getConnectionToken());
2809 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002810 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
2812}
2813
chaviw09c8d2d2020-08-24 15:48:26 -07002814std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2815 size_t size;
2816 switch (event.type) {
2817 case VerifiedInputEvent::Type::KEY: {
2818 size = sizeof(VerifiedKeyEvent);
2819 break;
2820 }
2821 case VerifiedInputEvent::Type::MOTION: {
2822 size = sizeof(VerifiedMotionEvent);
2823 break;
2824 }
2825 }
2826 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2827 return mHmacKeyManager.sign(start, size);
2828}
2829
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002830const std::array<uint8_t, 32> InputDispatcher::getSignature(
2831 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2832 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2833 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2834 // Only sign events up and down events as the purely move events
2835 // are tied to their up/down counterparts so signing would be redundant.
2836 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2837 verifiedEvent.actionMasked = actionMasked;
2838 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002839 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002840 }
2841 return INVALID_HMAC;
2842}
2843
2844const std::array<uint8_t, 32> InputDispatcher::getSignature(
2845 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2846 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2847 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2848 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002849 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002850}
2851
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853 const sp<Connection>& connection, uint32_t seq,
2854 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855#if DEBUG_DISPATCH_CYCLE
2856 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858#endif
2859
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 if (connection->status == Connection::STATUS_BROKEN ||
2861 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 return;
2863 }
2864
2865 // Notify other system components and prepare to start the next dispatch cycle.
2866 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2867}
2868
2869void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002870 const sp<Connection>& connection,
2871 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872#if DEBUG_DISPATCH_CYCLE
2873 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002874 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875#endif
2876
2877 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002878 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002879 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002880 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002881 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
2883 // The connection appears to be unrecoverably broken.
2884 // Ignore already broken or zombie connections.
2885 if (connection->status == Connection::STATUS_NORMAL) {
2886 connection->status = Connection::STATUS_BROKEN;
2887
2888 if (notify) {
2889 // Notify other system components.
2890 onDispatchCycleBrokenLocked(currentTime, connection);
2891 }
2892 }
2893}
2894
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002895void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2896 while (!queue.empty()) {
2897 DispatchEntry* dispatchEntry = queue.front();
2898 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002899 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
2901}
2902
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002903void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002905 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
2907 delete dispatchEntry;
2908}
2909
2910int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2911 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2912
2913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002914 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002916 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 "fd=%d, events=0x%x",
2919 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 return 0; // remove the callback
2921 }
2922
2923 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002924 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2926 if (!(events & ALOOPER_EVENT_INPUT)) {
2927 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 "events=0x%x",
2929 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 return 1;
2931 }
2932
2933 nsecs_t currentTime = now();
2934 bool gotOne = false;
2935 status_t status;
2936 for (;;) {
2937 uint32_t seq;
2938 bool handled;
2939 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2940 if (status) {
2941 break;
2942 }
2943 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2944 gotOne = true;
2945 }
2946 if (gotOne) {
2947 d->runCommandsLockedInterruptible();
2948 if (status == WOULD_BLOCK) {
2949 return 1;
2950 }
2951 }
2952
2953 notify = status != DEAD_OBJECT || !connection->monitor;
2954 if (notify) {
2955 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 }
2958 } else {
2959 // Monitor channels are never explicitly unregistered.
2960 // We do it automatically when the remote endpoint is closed so don't warn
2961 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002962 const bool stillHaveWindowHandle =
2963 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2964 nullptr;
2965 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966 if (notify) {
2967 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 "events=0x%x",
2969 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
2971 }
2972
Garfield Tan15601662020-09-22 15:32:38 -07002973 // Remove the channel.
2974 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977}
2978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002981 for (const auto& pair : mConnectionsByFd) {
2982 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 }
2984}
2985
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002987 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002988 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2989 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2990}
2991
2992void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2993 const CancelationOptions& options,
2994 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2995 for (const auto& it : monitorsByDisplay) {
2996 const std::vector<Monitor>& monitors = it.second;
2997 for (const Monitor& monitor : monitors) {
2998 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002999 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003000 }
3001}
3002
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003004 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003005 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003006 if (connection == nullptr) {
3007 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003009
3010 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011}
3012
3013void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3014 const sp<Connection>& connection, const CancelationOptions& options) {
3015 if (connection->status == Connection::STATUS_BROKEN) {
3016 return;
3017 }
3018
3019 nsecs_t currentTime = now();
3020
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003021 std::vector<EventEntry*> cancelationEvents =
3022 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003024 if (cancelationEvents.empty()) {
3025 return;
3026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003028 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3029 "with reality: %s, mode=%d.",
3030 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3031 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003033
3034 InputTarget target;
3035 sp<InputWindowHandle> windowHandle =
3036 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3037 if (windowHandle != nullptr) {
3038 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003039 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003040 target.globalScaleFactor = windowInfo->globalScaleFactor;
3041 }
3042 target.inputChannel = connection->inputChannel;
3043 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3044
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003045 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3046 EventEntry* cancelationEventEntry = cancelationEvents[i];
3047 switch (cancelationEventEntry->type) {
3048 case EventEntry::Type::KEY: {
3049 logOutboundKeyDetails("cancel - ",
3050 static_cast<const KeyEntry&>(*cancelationEventEntry));
3051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003053 case EventEntry::Type::MOTION: {
3054 logOutboundMotionDetails("cancel - ",
3055 static_cast<const MotionEntry&>(*cancelationEventEntry));
3056 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003058 case EventEntry::Type::FOCUS: {
3059 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3060 break;
3061 }
3062 case EventEntry::Type::CONFIGURATION_CHANGED:
3063 case EventEntry::Type::DEVICE_RESET: {
3064 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3065 EventEntry::typeToString(cancelationEventEntry->type));
3066 break;
3067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003070 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3071 target, InputTarget::FLAG_DISPATCH_AS_IS);
3072
3073 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003075
3076 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077}
3078
Svet Ganov5d3bc372020-01-26 23:11:07 -08003079void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3080 const sp<Connection>& connection) {
3081 if (connection->status == Connection::STATUS_BROKEN) {
3082 return;
3083 }
3084
3085 nsecs_t currentTime = now();
3086
3087 std::vector<EventEntry*> downEvents =
3088 connection->inputState.synthesizePointerDownEvents(currentTime);
3089
3090 if (downEvents.empty()) {
3091 return;
3092 }
3093
3094#if DEBUG_OUTBOUND_EVENT_DETAILS
3095 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3096 connection->getInputChannelName().c_str(), downEvents.size());
3097#endif
3098
3099 InputTarget target;
3100 sp<InputWindowHandle> windowHandle =
3101 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3102 if (windowHandle != nullptr) {
3103 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003104 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003105 target.globalScaleFactor = windowInfo->globalScaleFactor;
3106 }
3107 target.inputChannel = connection->inputChannel;
3108 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3109
3110 for (EventEntry* downEventEntry : downEvents) {
3111 switch (downEventEntry->type) {
3112 case EventEntry::Type::MOTION: {
3113 logOutboundMotionDetails("down - ",
3114 static_cast<const MotionEntry&>(*downEventEntry));
3115 break;
3116 }
3117
3118 case EventEntry::Type::KEY:
3119 case EventEntry::Type::FOCUS:
3120 case EventEntry::Type::CONFIGURATION_CHANGED:
3121 case EventEntry::Type::DEVICE_RESET: {
3122 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3123 EventEntry::typeToString(downEventEntry->type));
3124 break;
3125 }
3126 }
3127
3128 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3129 target, InputTarget::FLAG_DISPATCH_AS_IS);
3130
3131 downEventEntry->release();
3132 }
3133
3134 startDispatchCycleLocked(currentTime, connection);
3135}
3136
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003137MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003138 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 ALOG_ASSERT(pointerIds.value != 0);
3140
3141 uint32_t splitPointerIndexMap[MAX_POINTERS];
3142 PointerProperties splitPointerProperties[MAX_POINTERS];
3143 PointerCoords splitPointerCoords[MAX_POINTERS];
3144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003145 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 uint32_t splitPointerCount = 0;
3147
3148 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003151 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 uint32_t pointerId = uint32_t(pointerProperties.id);
3153 if (pointerIds.hasBit(pointerId)) {
3154 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3155 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3156 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003157 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 splitPointerCount += 1;
3159 }
3160 }
3161
3162 if (splitPointerCount != pointerIds.count()) {
3163 // This is bad. We are missing some of the pointers that we expected to deliver.
3164 // Most likely this indicates that we received an ACTION_MOVE events that has
3165 // different pointer ids than we expected based on the previous ACTION_DOWN
3166 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3167 // in this way.
3168 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 "we expected there to be %d pointers. This probably means we received "
3170 "a broken sequence of pointer ids from the input device.",
3171 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003172 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 }
3174
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003175 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3178 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3180 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003181 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 uint32_t pointerId = uint32_t(pointerProperties.id);
3183 if (pointerIds.hasBit(pointerId)) {
3184 if (pointerIds.count() == 1) {
3185 // The first/last pointer went down/up.
3186 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 ? AMOTION_EVENT_ACTION_DOWN
3188 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 } else {
3190 // A secondary pointer went down/up.
3191 uint32_t splitPointerIndex = 0;
3192 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3193 splitPointerIndex += 1;
3194 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 action = maskedAction |
3196 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198 } else {
3199 // An unrelated pointer changed.
3200 action = AMOTION_EVENT_ACTION_MOVE;
3201 }
3202 }
3203
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003204 int32_t newId = mIdGenerator.nextId();
3205 if (ATRACE_ENABLED()) {
3206 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3207 ") to MotionEvent(id=0x%" PRIx32 ").",
3208 originalMotionEntry.id, newId);
3209 ATRACE_NAME(message.c_str());
3210 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003211 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003212 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3213 originalMotionEntry.source, originalMotionEntry.displayId,
3214 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003215 originalMotionEntry.actionButton, originalMotionEntry.flags,
3216 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3217 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3218 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3219 originalMotionEntry.xCursorPosition,
3220 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003221 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 if (originalMotionEntry.injectionState) {
3224 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 splitMotionEntry->injectionState->refCount += 1;
3226 }
3227
3228 return splitMotionEntry;
3229}
3230
3231void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3232#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003233 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234#endif
3235
3236 bool needWake;
3237 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239
Prabir Pradhan42611e02018-11-27 14:04:02 -08003240 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003241 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 needWake = enqueueInboundEventLocked(newEntry);
3243 } // release lock
3244
3245 if (needWake) {
3246 mLooper->wake();
3247 }
3248}
3249
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003250/**
3251 * If one of the meta shortcuts is detected, process them here:
3252 * Meta + Backspace -> generate BACK
3253 * Meta + Enter -> generate HOME
3254 * This will potentially overwrite keyCode and metaState.
3255 */
3256void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003258 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3259 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3260 if (keyCode == AKEYCODE_DEL) {
3261 newKeyCode = AKEYCODE_BACK;
3262 } else if (keyCode == AKEYCODE_ENTER) {
3263 newKeyCode = AKEYCODE_HOME;
3264 }
3265 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003266 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003267 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003268 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003269 keyCode = newKeyCode;
3270 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3271 }
3272 } else if (action == AKEY_EVENT_ACTION_UP) {
3273 // In order to maintain a consistent stream of up and down events, check to see if the key
3274 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3275 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003276 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003277 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003278 auto replacementIt = mReplacedKeys.find(replacement);
3279 if (replacementIt != mReplacedKeys.end()) {
3280 keyCode = replacementIt->second;
3281 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003282 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3283 }
3284 }
3285}
3286
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3288#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3290 "policyFlags=0x%x, action=0x%x, "
3291 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3292 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3293 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3294 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#endif
3296 if (!validateKeyEvent(args->action)) {
3297 return;
3298 }
3299
3300 uint32_t policyFlags = args->policyFlags;
3301 int32_t flags = args->flags;
3302 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003303 // InputDispatcher tracks and generates key repeats on behalf of
3304 // whatever notifies it, so repeatCount should always be set to 0
3305 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3307 policyFlags |= POLICY_FLAG_VIRTUAL;
3308 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 if (policyFlags & POLICY_FLAG_FUNCTION) {
3311 metaState |= AMETA_FUNCTION_ON;
3312 }
3313
3314 policyFlags |= POLICY_FLAG_TRUSTED;
3315
Michael Wright78f24442014-08-06 15:55:28 -07003316 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003317 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003318
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003320 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003321 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3322 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323
Michael Wright2b3c3302018-03-02 17:19:13 +00003324 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003326 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3327 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 bool needWake;
3332 { // acquire lock
3333 mLock.lock();
3334
3335 if (shouldSendKeyToInputFilterLocked(args)) {
3336 mLock.unlock();
3337
3338 policyFlags |= POLICY_FLAG_FILTERED;
3339 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3340 return; // event was consumed by the filter
3341 }
3342
3343 mLock.lock();
3344 }
3345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003347 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 args->displayId, policyFlags, args->action, flags, keyCode,
3349 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
3351 needWake = enqueueInboundEventLocked(newEntry);
3352 mLock.unlock();
3353 } // release lock
3354
3355 if (needWake) {
3356 mLooper->wake();
3357 }
3358}
3359
3360bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3361 return mInputFilterEnabled;
3362}
3363
3364void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3365#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003366 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3367 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003368 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3369 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003370 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003371 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3372 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3373 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3374 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 for (uint32_t i = 0; i < args->pointerCount; i++) {
3376 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 "x=%f, y=%f, pressure=%f, size=%f, "
3378 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3379 "orientation=%f",
3380 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3381 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3382 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3383 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3384 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3385 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3386 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3387 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3388 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3389 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
3391#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3393 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return;
3395 }
3396
3397 uint32_t policyFlags = args->policyFlags;
3398 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003399
3400 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003401 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003402 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3403 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406
3407 bool needWake;
3408 { // acquire lock
3409 mLock.lock();
3410
3411 if (shouldSendMotionToInputFilterLocked(args)) {
3412 mLock.unlock();
3413
3414 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003415 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003416 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3417 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003418 args->metaState, args->buttonState, args->classification, transform,
3419 args->xPrecision, args->yPrecision, args->xCursorPosition,
3420 args->yCursorPosition, args->downTime, args->eventTime,
3421 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422
3423 policyFlags |= POLICY_FLAG_FILTERED;
3424 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3425 return; // event was consumed by the filter
3426 }
3427
3428 mLock.lock();
3429 }
3430
3431 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003432 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003433 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003434 args->displayId, policyFlags, args->action, args->actionButton,
3435 args->flags, args->metaState, args->buttonState,
3436 args->classification, args->edgeFlags, args->xPrecision,
3437 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3438 args->downTime, args->pointerCount, args->pointerProperties,
3439 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440
3441 needWake = enqueueInboundEventLocked(newEntry);
3442 mLock.unlock();
3443 } // release lock
3444
3445 if (needWake) {
3446 mLooper->wake();
3447 }
3448}
3449
3450bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003451 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452}
3453
3454void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3455#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003456 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 "switchMask=0x%08x",
3458 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460
3461 uint32_t policyFlags = args->policyFlags;
3462 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464}
3465
3466void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3467#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3469 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470#endif
3471
3472 bool needWake;
3473 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003474 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475
Prabir Pradhan42611e02018-11-27 14:04:02 -08003476 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003477 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 needWake = enqueueInboundEventLocked(newEntry);
3479 } // release lock
3480
3481 if (needWake) {
3482 mLooper->wake();
3483 }
3484}
3485
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003486int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3487 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003488 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489#if DEBUG_INBOUND_EVENT_DETAILS
3490 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003491 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3492 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003494 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495
3496 policyFlags |= POLICY_FLAG_INJECTED;
3497 if (hasInjectionPermission(injectorPid, injectorUid)) {
3498 policyFlags |= POLICY_FLAG_TRUSTED;
3499 }
3500
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003501 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003503 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003504 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3505 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003506 if (!validateKeyEvent(action)) {
3507 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003510 int32_t flags = incomingKey.getFlags();
3511 int32_t keyCode = incomingKey.getKeyCode();
3512 int32_t metaState = incomingKey.getMetaState();
3513 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003515 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003516 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003517 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3518 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3519 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3522 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003523 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524
3525 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3526 android::base::Timer t;
3527 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3528 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3529 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3530 std::to_string(t.duration().count()).c_str());
3531 }
3532 }
3533
3534 mLock.lock();
3535 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003536 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3537 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003538 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3539 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003540 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003541 injectedEntries.push(injectedEntry);
3542 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003545 case AINPUT_EVENT_TYPE_MOTION: {
3546 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3547 int32_t action = motionEvent->getAction();
3548 size_t pointerCount = motionEvent->getPointerCount();
3549 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3550 int32_t actionButton = motionEvent->getActionButton();
3551 int32_t displayId = motionEvent->getDisplayId();
3552 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3553 return INPUT_EVENT_INJECTION_FAILED;
3554 }
3555
3556 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3557 nsecs_t eventTime = motionEvent->getEventTime();
3558 android::base::Timer t;
3559 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3560 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3561 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3562 std::to_string(t.duration().count()).c_str());
3563 }
3564 }
3565
3566 mLock.lock();
3567 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3568 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3569 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003570 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3571 motionEvent->getSource(), motionEvent->getDisplayId(),
3572 policyFlags, action, actionButton, motionEvent->getFlags(),
3573 motionEvent->getMetaState(), motionEvent->getButtonState(),
3574 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3575 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003576 motionEvent->getRawXCursorPosition(),
3577 motionEvent->getRawYCursorPosition(),
3578 motionEvent->getDownTime(), uint32_t(pointerCount),
3579 pointerProperties, samplePointerCoords,
3580 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003581 injectedEntries.push(injectedEntry);
3582 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3583 sampleEventTimes += 1;
3584 samplePointerCoords += pointerCount;
3585 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003586 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003587 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 motionEvent->getDisplayId(), policyFlags, action,
3589 actionButton, motionEvent->getFlags(),
3590 motionEvent->getMetaState(), motionEvent->getButtonState(),
3591 motionEvent->getClassification(),
3592 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3593 motionEvent->getYPrecision(),
3594 motionEvent->getRawXCursorPosition(),
3595 motionEvent->getRawYCursorPosition(),
3596 motionEvent->getDownTime(), uint32_t(pointerCount),
3597 pointerProperties, samplePointerCoords,
3598 motionEvent->getXOffset(), motionEvent->getYOffset());
3599 injectedEntries.push(nextInjectedEntry);
3600 }
3601 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003604 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003605 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608
3609 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3610 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3611 injectionState->injectionIsAsync = true;
3612 }
3613
3614 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003615 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616
3617 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003618 while (!injectedEntries.empty()) {
3619 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3620 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622
3623 mLock.unlock();
3624
3625 if (needWake) {
3626 mLooper->wake();
3627 }
3628
3629 int32_t injectionResult;
3630 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003631 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632
3633 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3634 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3635 } else {
3636 for (;;) {
3637 injectionResult = injectionState->injectionResult;
3638 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3639 break;
3640 }
3641
3642 nsecs_t remainingTimeout = endTime - now();
3643 if (remainingTimeout <= 0) {
3644#if DEBUG_INJECTION
3645 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003646 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647#endif
3648 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3649 break;
3650 }
3651
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003652 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
3654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003655 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3656 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 while (injectionState->pendingForegroundDispatches != 0) {
3658#if DEBUG_INJECTION
3659 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661#endif
3662 nsecs_t remainingTimeout = endTime - now();
3663 if (remainingTimeout <= 0) {
3664#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3666 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667#endif
3668 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3669 break;
3670 }
3671
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003672 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674 }
3675 }
3676
3677 injectionState->release();
3678 } // release lock
3679
3680#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003681 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003682 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683#endif
3684
3685 return injectionResult;
3686}
3687
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003688std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003689 std::array<uint8_t, 32> calculatedHmac;
3690 std::unique_ptr<VerifiedInputEvent> result;
3691 switch (event.getType()) {
3692 case AINPUT_EVENT_TYPE_KEY: {
3693 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3694 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3695 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003696 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003697 break;
3698 }
3699 case AINPUT_EVENT_TYPE_MOTION: {
3700 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3701 VerifiedMotionEvent verifiedMotionEvent =
3702 verifiedMotionEventFromMotionEvent(motionEvent);
3703 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003704 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003705 break;
3706 }
3707 default: {
3708 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3709 return nullptr;
3710 }
3711 }
3712 if (calculatedHmac == INVALID_HMAC) {
3713 return nullptr;
3714 }
3715 if (calculatedHmac != event.getHmac()) {
3716 return nullptr;
3717 }
3718 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003719}
3720
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 return injectorUid == 0 ||
3723 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724}
3725
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003726void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 InjectionState* injectionState = entry->injectionState;
3728 if (injectionState) {
3729#if DEBUG_INJECTION
3730 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003731 "injectorPid=%d, injectorUid=%d",
3732 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733#endif
3734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 // Log the outcome since the injector did not wait for the injection result.
3737 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003738 case INPUT_EVENT_INJECTION_SUCCEEDED:
3739 ALOGV("Asynchronous input event injection succeeded.");
3740 break;
3741 case INPUT_EVENT_INJECTION_FAILED:
3742 ALOGW("Asynchronous input event injection failed.");
3743 break;
3744 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3745 ALOGW("Asynchronous input event injection permission denied.");
3746 break;
3747 case INPUT_EVENT_INJECTION_TIMED_OUT:
3748 ALOGW("Asynchronous input event injection timed out.");
3749 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
3751 }
3752
3753 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003754 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756}
3757
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003758void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 InjectionState* injectionState = entry->injectionState;
3760 if (injectionState) {
3761 injectionState->pendingForegroundDispatches += 1;
3762 }
3763}
3764
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003765void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 InjectionState* injectionState = entry->injectionState;
3767 if (injectionState) {
3768 injectionState->pendingForegroundDispatches -= 1;
3769
3770 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003771 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
3773 }
3774}
3775
Vishnu Nairad321cd2020-08-20 16:40:21 -07003776const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003777 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003778 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3779 auto it = mWindowHandlesByDisplay.find(displayId);
3780 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003781}
3782
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003784 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003785 if (windowHandleToken == nullptr) {
3786 return nullptr;
3787 }
3788
Arthur Hungb92218b2018-08-14 12:00:21 +08003789 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003790 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003791 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003792 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003793 return windowHandle;
3794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
3796 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003797 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798}
3799
Vishnu Nairad321cd2020-08-20 16:40:21 -07003800sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3801 int displayId) const {
3802 if (windowHandleToken == nullptr) {
3803 return nullptr;
3804 }
3805
3806 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3807 if (windowHandle->getToken() == windowHandleToken) {
3808 return windowHandle;
3809 }
3810 }
3811 return nullptr;
3812}
3813
3814sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3815 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3816 return getWindowHandleLocked(focusedToken, displayId);
3817}
3818
Mady Mellor017bcd12020-06-23 19:12:00 +00003819bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3820 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003821 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003822 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003823 if (handle->getId() == windowHandle->getId() &&
3824 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003825 if (windowHandle->getInfo()->displayId != it.first) {
3826 ALOGE("Found window %s in display %" PRId32
3827 ", but it should belong to display %" PRId32,
3828 windowHandle->getName().c_str(), it.first,
3829 windowHandle->getInfo()->displayId);
3830 }
3831 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
3834 }
3835 return false;
3836}
3837
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003838bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3839 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3840 const bool noInputChannel =
3841 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3842 if (connection != nullptr && noInputChannel) {
3843 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3844 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3845 return false;
3846 }
3847
3848 if (connection == nullptr) {
3849 if (!noInputChannel) {
3850 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3851 }
3852 return false;
3853 }
3854 if (!connection->responsive) {
3855 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3856 return false;
3857 }
3858 return true;
3859}
3860
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003861std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3862 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003863 size_t count = mInputChannelsByToken.count(token);
3864 if (count == 0) {
3865 return nullptr;
3866 }
3867 return mInputChannelsByToken.at(token);
3868}
3869
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003870void InputDispatcher::updateWindowHandlesForDisplayLocked(
3871 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3872 if (inputWindowHandles.empty()) {
3873 // Remove all handles on a display if there are no windows left.
3874 mWindowHandlesByDisplay.erase(displayId);
3875 return;
3876 }
3877
3878 // Since we compare the pointer of input window handles across window updates, we need
3879 // to make sure the handle object for the same window stays unchanged across updates.
3880 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003881 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003882 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003883 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003884 }
3885
3886 std::vector<sp<InputWindowHandle>> newHandles;
3887 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3888 if (!handle->updateInfo()) {
3889 // handle no longer valid
3890 continue;
3891 }
3892
3893 const InputWindowInfo* info = handle->getInfo();
3894 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3895 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3896 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003897 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3898 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3899 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003900 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003901 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003902 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003903 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003904 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003905 }
3906
3907 if (info->displayId != displayId) {
3908 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3909 handle->getName().c_str(), displayId, info->displayId);
3910 continue;
3911 }
3912
Robert Carredd13602020-04-13 17:24:34 -07003913 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3914 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003915 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003916 oldHandle->updateFrom(handle);
3917 newHandles.push_back(oldHandle);
3918 } else {
3919 newHandles.push_back(handle);
3920 }
3921 }
3922
3923 // Insert or replace
3924 mWindowHandlesByDisplay[displayId] = newHandles;
3925}
3926
Arthur Hung72d8dc32020-03-28 00:48:39 +00003927void InputDispatcher::setInputWindows(
3928 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3929 { // acquire lock
3930 std::scoped_lock _l(mLock);
3931 for (auto const& i : handlesPerDisplay) {
3932 setInputWindowsLocked(i.second, i.first);
3933 }
3934 }
3935 // Wake up poll loop since it may need to make new input dispatching choices.
3936 mLooper->wake();
3937}
3938
Arthur Hungb92218b2018-08-14 12:00:21 +08003939/**
3940 * Called from InputManagerService, update window handle list by displayId that can receive input.
3941 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3942 * If set an empty list, remove all handles from the specific display.
3943 * For focused handle, check if need to change and send a cancel event to previous one.
3944 * For removed handle, check if need to send a cancel event if already in touch.
3945 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003946void InputDispatcher::setInputWindowsLocked(
3947 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003948 if (DEBUG_FOCUS) {
3949 std::string windowList;
3950 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3951 windowList += iwh->getName() + " ";
3952 }
3953 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003956 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3957 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3958 const bool noInputWindow =
3959 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3960 if (noInputWindow && window->getToken() != nullptr) {
3961 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3962 window->getName().c_str());
3963 window->releaseChannel();
3964 }
3965 }
3966
Arthur Hung72d8dc32020-03-28 00:48:39 +00003967 // Copy old handles for release if they are no longer present.
3968 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Arthur Hung72d8dc32020-03-28 00:48:39 +00003970 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003971
Vishnu Nair958da932020-08-21 17:12:37 -07003972 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3973 if (mLastHoverWindowHandle &&
3974 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3975 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003976 mLastHoverWindowHandle = nullptr;
3977 }
3978
Vishnu Nair958da932020-08-21 17:12:37 -07003979 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3980 if (focusedToken) {
3981 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3982 if (result != FocusResult::OK) {
3983 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3984 }
3985 }
3986
3987 std::optional<FocusRequest> focusRequest =
3988 getOptionalValueByKey(mPendingFocusRequests, displayId);
3989 if (focusRequest) {
3990 // If the window from the pending request is now visible, provide it focus.
3991 FocusResult result = handleFocusRequestLocked(*focusRequest);
3992 if (result != FocusResult::NOT_VISIBLE) {
3993 // Drop the request if we were able to change the focus or we cannot change
3994 // it for another reason.
3995 mPendingFocusRequests.erase(displayId);
3996 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003999 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4000 mTouchStatesByDisplay.find(displayId);
4001 if (stateIt != mTouchStatesByDisplay.end()) {
4002 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004003 for (size_t i = 0; i < state.windows.size();) {
4004 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004005 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004006 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004007 ALOGD("Touched window was removed: %s in display %" PRId32,
4008 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004009 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004010 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004011 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4012 if (touchedInputChannel != nullptr) {
4013 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4014 "touched window was removed");
4015 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004017 state.windows.erase(state.windows.begin() + i);
4018 } else {
4019 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 }
4021 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004022 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004023
Arthur Hung72d8dc32020-03-28 00:48:39 +00004024 // Release information for windows that are no longer present.
4025 // This ensures that unused input channels are released promptly.
4026 // Otherwise, they might stick around until the window handle is destroyed
4027 // which might not happen until the next GC.
4028 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004029 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004030 if (DEBUG_FOCUS) {
4031 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004032 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004033 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004034 }
chaviw291d88a2019-02-14 10:33:58 -08004035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036}
4037
4038void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004039 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004040 if (DEBUG_FOCUS) {
4041 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4042 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4043 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004044 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Chris Yea209fde2020-07-22 13:54:51 -07004047 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004048 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004049
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004050 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4051 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004052 }
4053
Chris Yea209fde2020-07-22 13:54:51 -07004054 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004055 if (inputApplicationHandle != nullptr) {
4056 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4057 } else {
4058 mFocusedApplicationHandlesByDisplay.erase(displayId);
4059 }
4060
4061 // No matter what the old focused application was, stop waiting on it because it is
4062 // no longer focused.
4063 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 } // release lock
4065
4066 // Wake up poll loop since it may need to make new input dispatching choices.
4067 mLooper->wake();
4068}
4069
Tiger Huang721e26f2018-07-24 22:26:19 +08004070/**
4071 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4072 * the display not specified.
4073 *
4074 * We track any unreleased events for each window. If a window loses the ability to receive the
4075 * released event, we will send a cancel event to it. So when the focused display is changed, we
4076 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4077 * display. The display-specified events won't be affected.
4078 */
4079void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004080 if (DEBUG_FOCUS) {
4081 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4082 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004083 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004084 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004085
4086 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004087 sp<IBinder> oldFocusedWindowToken =
4088 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4089 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004090 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004091 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004092 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 CancelationOptions
4094 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4095 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004096 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004097 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4098 }
4099 }
4100 mFocusedDisplayId = displayId;
4101
Chris Ye3c2d6f52020-08-09 10:39:48 -07004102 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004103 sp<IBinder> newFocusedWindowToken =
4104 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4105 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004106
Vishnu Nairad321cd2020-08-20 16:40:21 -07004107 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004108 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004109 if (!mFocusedWindowTokenByDisplay.empty()) {
4110 ALOGE("But another display has a focused window\n%s",
4111 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004112 }
4113 }
4114 }
4115
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004116 if (DEBUG_FOCUS) {
4117 logDispatchStateLocked();
4118 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004119 } // release lock
4120
4121 // Wake up poll loop since it may need to make new input dispatching choices.
4122 mLooper->wake();
4123}
4124
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004126 if (DEBUG_FOCUS) {
4127 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
4130 bool changed;
4131 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004132 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
4134 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4135 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004136 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138
4139 if (mDispatchEnabled && !enabled) {
4140 resetAndDropEverythingLocked("dispatcher is being disabled");
4141 }
4142
4143 mDispatchEnabled = enabled;
4144 mDispatchFrozen = frozen;
4145 changed = true;
4146 } else {
4147 changed = false;
4148 }
4149
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004150 if (DEBUG_FOCUS) {
4151 logDispatchStateLocked();
4152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 } // release lock
4154
4155 if (changed) {
4156 // Wake up poll loop since it may need to make new input dispatching choices.
4157 mLooper->wake();
4158 }
4159}
4160
4161void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004162 if (DEBUG_FOCUS) {
4163 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165
4166 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004167 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
4169 if (mInputFilterEnabled == enabled) {
4170 return;
4171 }
4172
4173 mInputFilterEnabled = enabled;
4174 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4175 } // release lock
4176
4177 // Wake up poll loop since there might be work to do to drop everything.
4178 mLooper->wake();
4179}
4180
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004181void InputDispatcher::setInTouchMode(bool inTouchMode) {
4182 std::scoped_lock lock(mLock);
4183 mInTouchMode = inTouchMode;
4184}
4185
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004186void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4187 if (opacity < 0 || opacity > 1) {
4188 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4189 return;
4190 }
4191
4192 std::scoped_lock lock(mLock);
4193 mMaximumObscuringOpacityForTouch = opacity;
4194}
4195
4196void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4197 std::scoped_lock lock(mLock);
4198 mBlockUntrustedTouchesMode = mode;
4199}
4200
chaviwfbe5d9c2018-12-26 12:23:37 -08004201bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4202 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004203 if (DEBUG_FOCUS) {
4204 ALOGD("Trivial transfer to same window.");
4205 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004206 return true;
4207 }
4208
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004210 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
chaviwfbe5d9c2018-12-26 12:23:37 -08004212 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4213 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004214 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004215 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 return false;
4217 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004218 if (DEBUG_FOCUS) {
4219 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4220 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004223 if (DEBUG_FOCUS) {
4224 ALOGD("Cannot transfer focus because windows are on different displays.");
4225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 return false;
4227 }
4228
4229 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004230 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4231 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004232 for (size_t i = 0; i < state.windows.size(); i++) {
4233 const TouchedWindow& touchedWindow = state.windows[i];
4234 if (touchedWindow.windowHandle == fromWindowHandle) {
4235 int32_t oldTargetFlags = touchedWindow.targetFlags;
4236 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004238 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 int32_t newTargetFlags = oldTargetFlags &
4241 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4242 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004243 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244
Jeff Brownf086ddb2014-02-11 14:28:48 -08004245 found = true;
4246 goto Found;
4247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 }
4249 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004253 if (DEBUG_FOCUS) {
4254 ALOGD("Focus transfer failed because from window did not have focus.");
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 return false;
4257 }
4258
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004259 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4260 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004261 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004262 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 CancelationOptions
4264 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4265 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004267 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004270 if (DEBUG_FOCUS) {
4271 logDispatchStateLocked();
4272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 } // release lock
4274
4275 // Wake up poll loop since it may need to make new input dispatching choices.
4276 mLooper->wake();
4277 return true;
4278}
4279
4280void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004281 if (DEBUG_FOCUS) {
4282 ALOGD("Resetting and dropping all events (%s).", reason);
4283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
4285 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4286 synthesizeCancelationEventsForAllConnectionsLocked(options);
4287
4288 resetKeyRepeatLocked();
4289 releasePendingEventLocked();
4290 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004291 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004293 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004294 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004296 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297}
4298
4299void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004300 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 dumpDispatchStateLocked(dump);
4302
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004303 std::istringstream stream(dump);
4304 std::string line;
4305
4306 while (std::getline(stream, line, '\n')) {
4307 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309}
4310
Vishnu Nairad321cd2020-08-20 16:40:21 -07004311std::string InputDispatcher::dumpFocusedWindowsLocked() {
4312 if (mFocusedWindowTokenByDisplay.empty()) {
4313 return INDENT "FocusedWindows: <none>\n";
4314 }
4315
4316 std::string dump;
4317 dump += INDENT "FocusedWindows:\n";
4318 for (auto& it : mFocusedWindowTokenByDisplay) {
4319 const int32_t displayId = it.first;
4320 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4321 if (windowHandle) {
4322 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4323 windowHandle->getName().c_str());
4324 } else {
4325 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4326 " has focused token without a window'\n",
4327 displayId);
4328 }
4329 }
4330 return dump;
4331}
4332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004334 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4335 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4336 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004337 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
Tiger Huang721e26f2018-07-24 22:26:19 +08004339 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4340 dump += StringPrintf(INDENT "FocusedApplications:\n");
4341 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4342 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004343 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004344 const std::chrono::duration timeout =
4345 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004347 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004348 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004351 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004353
Vishnu Nairad321cd2020-08-20 16:40:21 -07004354 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004356 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004357 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004358 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4359 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004360 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 state.displayId, toString(state.down), toString(state.split),
4362 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004363 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004364 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004365 for (size_t i = 0; i < state.windows.size(); i++) {
4366 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 dump += StringPrintf(INDENT4
4368 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4369 i, touchedWindow.windowHandle->getName().c_str(),
4370 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004371 }
4372 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004373 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004374 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004375 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004376 dump += INDENT3 "Portal windows:\n";
4377 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004378 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004379 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4380 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004381 }
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 }
4384 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004385 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 }
4387
Arthur Hungb92218b2018-08-14 12:00:21 +08004388 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004390 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004391 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004392 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004393 dump += INDENT2 "Windows:\n";
4394 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004395 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004396 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397
Arthur Hungb92218b2018-08-14 12:00:21 +08004398 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004399 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4400 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004401 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004403 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004404 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 i, windowInfo->name.c_str(), windowInfo->displayId,
4406 windowInfo->portalToDisplayId,
4407 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004408 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 toString(windowInfo->hasWallpaper),
4410 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004411 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004412 static_cast<int32_t>(windowInfo->type),
4413 windowInfo->frameLeft, windowInfo->frameTop,
4414 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004415 windowInfo->globalScaleFactor,
4416 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004417 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004418 dump += StringPrintf(", inputFeatures=%s",
4419 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004420 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4421 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004423 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004424 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004425 }
4426 } else {
4427 dump += INDENT2 "Windows: <none>\n";
4428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 }
4430 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004431 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 }
4433
Michael Wright3dd60e22019-03-27 22:06:44 +00004434 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004435 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004436 const std::vector<Monitor>& monitors = it.second;
4437 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4438 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 }
4440 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004441 const std::vector<Monitor>& monitors = it.second;
4442 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4443 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 }
4448
4449 nsecs_t currentTime = now();
4450
4451 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004452 if (!mRecentQueue.empty()) {
4453 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4454 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004455 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004457 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 }
4459 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004460 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 }
4462
4463 // Dump event currently being dispatched.
4464 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004465 dump += INDENT "PendingEvent:\n";
4466 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004468 dump += StringPrintf(", age=%" PRId64 "ms\n",
4469 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004471 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 }
4473
4474 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004475 if (!mInboundQueue.empty()) {
4476 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4477 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004478 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004480 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 }
4482 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004483 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
4485
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004486 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004487 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004488 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4489 const KeyReplacement& replacement = pair.first;
4490 int32_t newKeyCode = pair.second;
4491 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004492 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004493 }
4494 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004495 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004496 }
4497
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004498 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004499 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004500 for (const auto& pair : mConnectionsByFd) {
4501 const sp<Connection>& connection = pair.second;
4502 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004503 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004504 pair.first, connection->getInputChannelName().c_str(),
4505 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004506 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004508 if (!connection->outboundQueue.empty()) {
4509 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4510 connection->outboundQueue.size());
4511 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 dump.append(INDENT4);
4513 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4515 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004516 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004517 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004520 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 }
4522
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004523 if (!connection->waitQueue.empty()) {
4524 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4525 connection->waitQueue.size());
4526 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004527 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004529 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004530 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004532 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004533 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 }
4535 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004536 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 }
4538 }
4539 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004540 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 }
4542
4543 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004544 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4545 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004547 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 }
4549
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004550 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004551 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4552 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4553 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554}
4555
Michael Wright3dd60e22019-03-27 22:06:44 +00004556void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4557 const size_t numMonitors = monitors.size();
4558 for (size_t i = 0; i < numMonitors; i++) {
4559 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004560 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004561 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4562 dump += "\n";
4563 }
4564}
4565
Garfield Tan15601662020-09-22 15:32:38 -07004566base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4567 const std::string& name) {
4568#if DEBUG_CHANNEL_CREATION
4569 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570#endif
4571
Garfield Tan15601662020-09-22 15:32:38 -07004572 std::shared_ptr<InputChannel> serverChannel;
4573 std::unique_ptr<InputChannel> clientChannel;
4574 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4575
4576 if (result) {
4577 return base::Error(result) << "Failed to open input channel pair with name " << name;
4578 }
4579
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004581 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004582 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583
Garfield Tan15601662020-09-22 15:32:38 -07004584 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004585 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004586 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4589 } // release lock
4590
4591 // Wake the looper because some connections have changed.
4592 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004593 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594}
4595
Garfield Tan15601662020-09-22 15:32:38 -07004596base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4597 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4598 std::shared_ptr<InputChannel> serverChannel;
4599 std::unique_ptr<InputChannel> clientChannel;
4600 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4601 if (result) {
4602 return base::Error(result) << "Failed to open input channel pair with name " << name;
4603 }
4604
Michael Wright3dd60e22019-03-27 22:06:44 +00004605 { // acquire lock
4606 std::scoped_lock _l(mLock);
4607
4608 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004609 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4610 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004611 }
4612
Garfield Tan15601662020-09-22 15:32:38 -07004613 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004614
Garfield Tan15601662020-09-22 15:32:38 -07004615 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004616 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004617 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619 auto& monitorsByDisplay =
4620 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004621 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004622
4623 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004624 }
Garfield Tan15601662020-09-22 15:32:38 -07004625
Michael Wright3dd60e22019-03-27 22:06:44 +00004626 // Wake the looper because some connections have changed.
4627 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004628 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004629}
4630
Garfield Tan15601662020-09-22 15:32:38 -07004631status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004633 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634
Garfield Tan15601662020-09-22 15:32:38 -07004635 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 if (status) {
4637 return status;
4638 }
4639 } // release lock
4640
4641 // Wake the poll loop because removing the connection may have changed the current
4642 // synchronization state.
4643 mLooper->wake();
4644 return OK;
4645}
4646
Garfield Tan15601662020-09-22 15:32:38 -07004647status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4648 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004649 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004650 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004651 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 return BAD_VALUE;
4653 }
4654
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004655 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004656 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004657
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004659 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 }
4661
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004662 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
4664 nsecs_t currentTime = now();
4665 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4666
4667 connection->status = Connection::STATUS_ZOMBIE;
4668 return OK;
4669}
4670
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004671void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4672 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4673 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004674}
4675
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004676void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004677 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004678 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004680 std::vector<Monitor>& monitors = it->second;
4681 const size_t numMonitors = monitors.size();
4682 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004683 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 monitors.erase(monitors.begin() + i);
4685 break;
4686 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004687 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004688 if (monitors.empty()) {
4689 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004690 } else {
4691 ++it;
4692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 }
4694}
4695
Michael Wright3dd60e22019-03-27 22:06:44 +00004696status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4697 { // acquire lock
4698 std::scoped_lock _l(mLock);
4699 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4700
4701 if (!foundDisplayId) {
4702 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4703 return BAD_VALUE;
4704 }
4705 int32_t displayId = foundDisplayId.value();
4706
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004707 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4708 mTouchStatesByDisplay.find(displayId);
4709 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004710 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4711 return BAD_VALUE;
4712 }
4713
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004714 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004715 std::optional<int32_t> foundDeviceId;
4716 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004717 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004718 foundDeviceId = state.deviceId;
4719 }
4720 }
4721 if (!foundDeviceId || !state.down) {
4722 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004724 return BAD_VALUE;
4725 }
4726 int32_t deviceId = foundDeviceId.value();
4727
4728 // Send cancel events to all the input channels we're stealing from.
4729 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004731 options.deviceId = deviceId;
4732 options.displayId = displayId;
4733 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004734 std::shared_ptr<InputChannel> channel =
4735 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004736 if (channel != nullptr) {
4737 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4738 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004739 }
4740 // Then clear the current touch state so we stop dispatching to them as well.
4741 state.filterNonMonitors();
4742 }
4743 return OK;
4744}
4745
Michael Wright3dd60e22019-03-27 22:06:44 +00004746std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4747 const sp<IBinder>& token) {
4748 for (const auto& it : mGestureMonitorsByDisplay) {
4749 const std::vector<Monitor>& monitors = it.second;
4750 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004751 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004752 return it.first;
4753 }
4754 }
4755 }
4756 return std::nullopt;
4757}
4758
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004759sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004760 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004761 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004762 }
4763
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004764 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004765 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004766 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004767 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 }
4769 }
Robert Carr4e670e52018-08-15 13:26:12 -07004770
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004771 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772}
4773
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004774void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004775 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004776 removeByValue(mConnectionsByFd, connection);
4777}
4778
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4780 const sp<Connection>& connection, uint32_t seq,
4781 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004782 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4783 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 commandEntry->connection = connection;
4785 commandEntry->eventTime = currentTime;
4786 commandEntry->seq = seq;
4787 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004788 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789}
4790
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4792 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004796 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4797 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004799 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800}
4801
Vishnu Nairad321cd2020-08-20 16:40:21 -07004802void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4803 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004804 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4805 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004806 commandEntry->oldToken = oldToken;
4807 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004808 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004809}
4810
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004811void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4813 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004814 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004815 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004816 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 return;
4818 }
4819 /**
4820 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4821 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4822 * has changed. This could cause newer entries to time out before the already dispatched
4823 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4824 * processes the events linearly. So providing information about the oldest entry seems to be
4825 * most useful.
4826 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004827 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4829 std::string reason =
4830 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004831 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832 ns2ms(currentWait),
4833 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004835 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 reason);
4837
4838 std::unique_ptr<CommandEntry> commandEntry =
4839 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4840 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004841 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842 commandEntry->reason = std::move(reason);
4843 postCommandLocked(std::move(commandEntry));
4844}
4845
Chris Yea209fde2020-07-22 13:54:51 -07004846void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4848 application->getName().c_str());
4849
4850 updateLastAnrStateLocked(application, reason);
4851
4852 std::unique_ptr<CommandEntry> commandEntry =
4853 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4854 commandEntry->inputApplicationHandle = application;
4855 commandEntry->inputChannel = nullptr;
4856 commandEntry->reason = std::move(reason);
4857 postCommandLocked(std::move(commandEntry));
4858}
4859
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004860void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4861 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4862 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4863 commandEntry->obscuringPackage = obscuringPackage;
4864 postCommandLocked(std::move(commandEntry));
4865}
4866
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4868 const std::string& reason) {
4869 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4870 updateLastAnrStateLocked(windowLabel, reason);
4871}
4872
Chris Yea209fde2020-07-22 13:54:51 -07004873void InputDispatcher::updateLastAnrStateLocked(
4874 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4876 updateLastAnrStateLocked(windowLabel, reason);
4877}
4878
4879void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4880 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004882 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 struct tm tm;
4884 localtime_r(&t, &tm);
4885 char timestr[64];
4886 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004887 mLastAnrState.clear();
4888 mLastAnrState += INDENT "ANR:\n";
4889 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4891 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004892 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004895void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 mLock.unlock();
4897
4898 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4899
4900 mLock.lock();
4901}
4902
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004903void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 sp<Connection> connection = commandEntry->connection;
4905
4906 if (connection->status != Connection::STATUS_ZOMBIE) {
4907 mLock.unlock();
4908
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004909 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
4911 mLock.lock();
4912 }
4913}
4914
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004915void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004916 sp<IBinder> oldToken = commandEntry->oldToken;
4917 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004918 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004919 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004920 mLock.lock();
4921}
4922
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004923void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004924 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004925 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mLock.unlock();
4927
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004928 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004929 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
4931 mLock.lock();
4932
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004933 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4935 } else {
4936 // stop waking up for events in this connection, it is already not responding
4937 sp<Connection> connection = getConnectionLocked(token);
4938 if (connection == nullptr) {
4939 return;
4940 }
4941 cancelEventsForAnrLocked(connection);
4942 }
4943}
4944
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004945void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
4946 mLock.unlock();
4947
4948 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
4949
4950 mLock.lock();
4951}
4952
Chris Yea209fde2020-07-22 13:54:51 -07004953void InputDispatcher::extendAnrTimeoutsLocked(
4954 const std::shared_ptr<InputApplicationHandle>& application,
4955 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004956 if (connectionToken == nullptr && application != nullptr) {
4957 // The ANR happened because there's no focused window
4958 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4959 mAwaitedFocusedApplication = application;
4960 }
4961
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 sp<Connection> connection = getConnectionLocked(connectionToken);
4963 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004964 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965 return;
4966 }
4967
4968 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004969 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004970
4971 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004972 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004973 for (DispatchEntry* entry : connection->waitQueue) {
4974 if (newTimeout >= entry->timeoutTime) {
4975 // Already removed old entries when connection was marked unresponsive
4976 entry->timeoutTime = newTimeout;
4977 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4978 }
4979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980}
4981
4982void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4983 CommandEntry* commandEntry) {
4984 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004985 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
4987 mLock.unlock();
4988
Michael Wright2b3c3302018-03-02 17:19:13 +00004989 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004991 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004992 : nullptr;
4993 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004994 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4995 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
4999 mLock.lock();
5000
5001 if (delay < 0) {
5002 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5003 } else if (!delay) {
5004 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5005 } else {
5006 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5007 entry->interceptKeyWakeupTime = now() + delay;
5008 }
5009 entry->release();
5010}
5011
chaviwfd6d3512019-03-25 13:23:49 -07005012void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5013 mLock.unlock();
5014 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5015 mLock.lock();
5016}
5017
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005018/**
5019 * Connection is responsive if it has no events in the waitQueue that are older than the
5020 * current time.
5021 */
5022static bool isConnectionResponsive(const Connection& connection) {
5023 const nsecs_t currentTime = now();
5024 for (const DispatchEntry* entry : connection.waitQueue) {
5025 if (entry->timeoutTime < currentTime) {
5026 return false;
5027 }
5028 }
5029 return true;
5030}
5031
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005032void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005034 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005036 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037
5038 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005039 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005040 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005041 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005043 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005044 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005045 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005046 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5047 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005048 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005049 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005050
5051 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005052 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005053 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5054 restartEvent =
5055 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005056 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005057 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5058 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5059 handled);
5060 } else {
5061 restartEvent = false;
5062 }
5063
5064 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005065 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005066 // contents of the wait queue to have been drained, so we need to double-check
5067 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005068 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5069 if (dispatchEntryIt != connection->waitQueue.end()) {
5070 dispatchEntry = *dispatchEntryIt;
5071 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005072 mAnrTracker.erase(dispatchEntry->timeoutTime,
5073 connection->inputChannel->getConnectionToken());
5074 if (!connection->responsive) {
5075 connection->responsive = isConnectionResponsive(*connection);
5076 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005077 traceWaitQueueLength(connection);
5078 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005079 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005080 traceOutboundQueueLength(connection);
5081 } else {
5082 releaseDispatchEntry(dispatchEntry);
5083 }
5084 }
5085
5086 // Start the next dispatch cycle for this connection.
5087 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088}
5089
5090bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005091 DispatchEntry* dispatchEntry,
5092 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005093 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005094 if (!handled) {
5095 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005096 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005097 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005098 return false;
5099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005101 // Get the fallback key state.
5102 // Clear it out after dispatching the UP.
5103 int32_t originalKeyCode = keyEntry->keyCode;
5104 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5105 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5106 connection->inputState.removeFallbackKey(originalKeyCode);
5107 }
5108
5109 if (handled || !dispatchEntry->hasForegroundTarget()) {
5110 // If the application handles the original key for which we previously
5111 // generated a fallback or if the window is not a foreground window,
5112 // then cancel the associated fallback key, if any.
5113 if (fallbackKeyCode != -1) {
5114 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005116 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005117 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5118 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5119 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005121 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005122 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
5124 mLock.unlock();
5125
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005126 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005127 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128
5129 mLock.lock();
5130
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005131 // Cancel the fallback key.
5132 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005134 "application handled the original non-fallback key "
5135 "or is no longer a foreground target, "
5136 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 options.keyCode = fallbackKeyCode;
5138 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005140 connection->inputState.removeFallbackKey(originalKeyCode);
5141 }
5142 } else {
5143 // If the application did not handle a non-fallback key, first check
5144 // that we are in a good state to perform unhandled key event processing
5145 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005146 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005147 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005149 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005150 "since this is not an initial down. "
5151 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5152 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005154 return false;
5155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005157 // Dispatch the unhandled key to the policy.
5158#if DEBUG_OUTBOUND_EVENT_DETAILS
5159 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005160 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5161 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005162#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005163 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005164
5165 mLock.unlock();
5166
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005167 bool fallback =
5168 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5169 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005170
5171 mLock.lock();
5172
5173 if (connection->status != Connection::STATUS_NORMAL) {
5174 connection->inputState.removeFallbackKey(originalKeyCode);
5175 return false;
5176 }
5177
5178 // Latch the fallback keycode for this key on an initial down.
5179 // The fallback keycode cannot change at any other point in the lifecycle.
5180 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005182 fallbackKeyCode = event.getKeyCode();
5183 } else {
5184 fallbackKeyCode = AKEYCODE_UNKNOWN;
5185 }
5186 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5187 }
5188
5189 ALOG_ASSERT(fallbackKeyCode != -1);
5190
5191 // Cancel the fallback key if the policy decides not to send it anymore.
5192 // We will continue to dispatch the key to the policy but we will no
5193 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005194 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5195 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005196#if DEBUG_OUTBOUND_EVENT_DETAILS
5197 if (fallback) {
5198 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005199 "as a fallback for %d, but on the DOWN it had requested "
5200 "to send %d instead. Fallback canceled.",
5201 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005202 } else {
5203 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 "but on the DOWN it had requested to send %d. "
5205 "Fallback canceled.",
5206 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005207 }
5208#endif
5209
5210 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5211 "canceling fallback, policy no longer desires it");
5212 options.keyCode = fallbackKeyCode;
5213 synthesizeCancelationEventsForConnectionLocked(connection, options);
5214
5215 fallback = false;
5216 fallbackKeyCode = AKEYCODE_UNKNOWN;
5217 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005218 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005219 }
5220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
5222#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005223 {
5224 std::string msg;
5225 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5226 connection->inputState.getFallbackKeys();
5227 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005228 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005230 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005231 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005232 }
5233#endif
5234
5235 if (fallback) {
5236 // Restart the dispatch cycle using the fallback key.
5237 keyEntry->eventTime = event.getEventTime();
5238 keyEntry->deviceId = event.getDeviceId();
5239 keyEntry->source = event.getSource();
5240 keyEntry->displayId = event.getDisplayId();
5241 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5242 keyEntry->keyCode = fallbackKeyCode;
5243 keyEntry->scanCode = event.getScanCode();
5244 keyEntry->metaState = event.getMetaState();
5245 keyEntry->repeatCount = event.getRepeatCount();
5246 keyEntry->downTime = event.getDownTime();
5247 keyEntry->syntheticRepeat = false;
5248
5249#if DEBUG_OUTBOUND_EVENT_DETAILS
5250 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005251 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5252 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005253#endif
5254 return true; // restart the event
5255 } else {
5256#if DEBUG_OUTBOUND_EVENT_DETAILS
5257 ALOGD("Unhandled key event: No fallback key.");
5258#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005259
5260 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005261 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263 }
5264 return false;
5265}
5266
5267bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 DispatchEntry* dispatchEntry,
5269 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 return false;
5271}
5272
5273void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5274 mLock.unlock();
5275
5276 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5277
5278 mLock.lock();
5279}
5280
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005281KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5282 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005283 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005284 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5285 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005286 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287}
5288
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005289void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5290 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 // TODO Write some statistics about how long we spend waiting.
5292}
5293
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005294/**
5295 * Report the touch event latency to the statsd server.
5296 * Input events are reported for statistics if:
5297 * - This is a touchscreen event
5298 * - InputFilter is not enabled
5299 * - Event is not injected or synthesized
5300 *
5301 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5302 * from getting aggregated with the "old" data.
5303 */
5304void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5305 REQUIRES(mLock) {
5306 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5307 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5308 if (!reportForStatistics) {
5309 return;
5310 }
5311
5312 if (mTouchStatistics.shouldReport()) {
5313 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5314 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5315 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5316 mTouchStatistics.reset();
5317 }
5318 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5319 mTouchStatistics.addValue(latencyMicros);
5320}
5321
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322void InputDispatcher::traceInboundQueueLengthLocked() {
5323 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005324 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
5326}
5327
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005328void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 if (ATRACE_ENABLED()) {
5330 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005331 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005332 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 }
5334}
5335
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005336void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 if (ATRACE_ENABLED()) {
5338 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005339 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005340 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
5342}
5343
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005344void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005347 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 dumpDispatchStateLocked(dump);
5349
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005350 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005351 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005352 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 }
5354}
5355
5356void InputDispatcher::monitor() {
5357 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005358 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005360 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361}
5362
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005363/**
5364 * Wake up the dispatcher and wait until it processes all events and commands.
5365 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5366 * this method can be safely called from any thread, as long as you've ensured that
5367 * the work you are interested in completing has already been queued.
5368 */
5369bool InputDispatcher::waitForIdle() {
5370 /**
5371 * Timeout should represent the longest possible time that a device might spend processing
5372 * events and commands.
5373 */
5374 constexpr std::chrono::duration TIMEOUT = 100ms;
5375 std::unique_lock lock(mLock);
5376 mLooper->wake();
5377 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5378 return result == std::cv_status::no_timeout;
5379}
5380
Vishnu Naire798b472020-07-23 13:52:21 -07005381/**
5382 * Sets focus to the window identified by the token. This must be called
5383 * after updating any input window handles.
5384 *
5385 * Params:
5386 * request.token - input channel token used to identify the window that should gain focus.
5387 * request.focusedToken - the token that the caller expects currently to be focused. If the
5388 * specified token does not match the currently focused window, this request will be dropped.
5389 * If the specified focused token matches the currently focused window, the call will succeed.
5390 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5391 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5392 * when requesting the focus change. This determines which request gets
5393 * precedence if there is a focus change request from another source such as pointer down.
5394 */
Vishnu Nair958da932020-08-21 17:12:37 -07005395void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5396 { // acquire lock
5397 std::scoped_lock _l(mLock);
5398
5399 const int32_t displayId = request.displayId;
5400 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5401 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5402 ALOGD_IF(DEBUG_FOCUS,
5403 "setFocusedWindow on display %" PRId32
5404 " ignored, reason: focusedToken is not focused",
5405 displayId);
5406 return;
5407 }
5408
5409 mPendingFocusRequests.erase(displayId);
5410 FocusResult result = handleFocusRequestLocked(request);
5411 if (result == FocusResult::NOT_VISIBLE) {
5412 // The requested window is not currently visible. Wait for the window to become visible
5413 // and then provide it focus. This is to handle situations where a user action triggers
5414 // a new window to appear. We want to be able to queue any key events after the user
5415 // action and deliver it to the newly focused window. In order for this to happen, we
5416 // take focus from the currently focused window so key events can be queued.
5417 ALOGD_IF(DEBUG_FOCUS,
5418 "setFocusedWindow on display %" PRId32
5419 " pending, reason: window is not visible",
5420 displayId);
5421 mPendingFocusRequests[displayId] = request;
5422 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5423 "setFocusedWindow_AwaitingWindowVisibility");
5424 } else if (result != FocusResult::OK) {
5425 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5426 typeToString(result));
5427 }
5428 } // release lock
5429 // Wake up poll loop since it may need to make new input dispatching choices.
5430 mLooper->wake();
5431}
5432
5433InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5434 const FocusRequest& request) {
5435 const int32_t displayId = request.displayId;
5436 const sp<IBinder> newFocusedToken = request.token;
5437 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5438
5439 if (oldFocusedToken == request.token) {
5440 ALOGD_IF(DEBUG_FOCUS,
5441 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5442 displayId);
5443 return FocusResult::OK;
5444 }
5445
5446 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5447 if (result != FocusResult::OK) {
5448 return result;
5449 }
5450
5451 std::string_view reason =
5452 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5453 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5454 return FocusResult::OK;
5455}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005456
Vishnu Nairad321cd2020-08-20 16:40:21 -07005457void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5458 const sp<IBinder>& newFocusedToken, int32_t displayId,
5459 std::string_view reason) {
5460 if (oldFocusedToken) {
5461 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005462 if (focusedInputChannel) {
5463 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5464 "focus left window");
5465 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005466 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005467 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005468 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005469 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005470 if (newFocusedToken) {
5471 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5472 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005473 }
5474
5475 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005476 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005477 }
5478}
Vishnu Nair958da932020-08-21 17:12:37 -07005479
5480/**
5481 * Checks if the window token can be focused on a display. The token can be focused if there is
5482 * at least one window handle that is visible with the same token and all window handles with the
5483 * same token are focusable.
5484 *
5485 * In the case of mirroring, two windows may share the same window token and their visibility
5486 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5487 * we expect the focusability of the windows to match since its hard to reason why one window can
5488 * receive focus events and the other cannot when both are backed by the same input channel.
5489 */
5490InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5491 int32_t displayId) const {
5492 bool allWindowsAreFocusable = true;
5493 bool visibleWindowFound = false;
5494 bool windowFound = false;
5495 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5496 if (window->getToken() != token) {
5497 continue;
5498 }
5499 windowFound = true;
5500 if (window->getInfo()->visible) {
5501 // Check if at least a single window is visible.
5502 visibleWindowFound = true;
5503 }
5504 if (!window->getInfo()->focusable) {
5505 // Check if all windows with the window token are focusable.
5506 allWindowsAreFocusable = false;
5507 break;
5508 }
5509 }
5510
5511 if (!windowFound) {
5512 return FocusResult::NO_WINDOW;
5513 }
5514 if (!allWindowsAreFocusable) {
5515 return FocusResult::NOT_FOCUSABLE;
5516 }
5517 if (!visibleWindowFound) {
5518 return FocusResult::NOT_VISIBLE;
5519 }
5520
5521 return FocusResult::OK;
5522}
Garfield Tane84e6f92019-08-29 17:28:41 -07005523} // namespace android::inputdispatcher