blob: ab0d340363aebec0eb04d378e9f711956b6b69b1 [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/**
485 * Check if any of the connections' wait queues have events that are too old.
486 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
487 * Return the time at which we should wake up next.
488 */
489nsecs_t InputDispatcher::processAnrsLocked() {
490 const nsecs_t currentTime = now();
491 nsecs_t nextAnrCheck = LONG_LONG_MAX;
492 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
493 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
494 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
495 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700496 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700497 return LONG_LONG_MIN;
498 } else {
499 // Keep waiting
500 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
501 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
502 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
503 }
504 }
505
506 // Check if any connection ANRs are due
507 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
508 if (currentTime < nextAnrCheck) { // most likely scenario
509 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
510 }
511
512 // If we reached here, we have an unresponsive connection.
513 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
514 if (connection == nullptr) {
515 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
516 return nextAnrCheck;
517 }
518 connection->responsive = false;
519 // Stop waking up for this unresponsive connection
520 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500521 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700522 return LONG_LONG_MIN;
523}
524
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500525std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700526 sp<InputWindowHandle> window = getWindowHandleLocked(token);
527 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500528 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700529 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500530 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700531}
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
534 nsecs_t currentTime = now();
535
Jeff Browndc5992e2014-04-11 01:27:26 -0700536 // Reset the key repeat timer whenever normal dispatch is suspended while the
537 // device is in a non-interactive state. This is to ensure that we abort a key
538 // repeat if the device is just coming out of sleep.
539 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 resetKeyRepeatLocked();
541 }
542
543 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
544 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100545 if (DEBUG_FOCUS) {
546 ALOGD("Dispatch frozen. Waiting some more.");
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 return;
549 }
550
551 // Optimize latency of app switches.
552 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
553 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
554 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
555 if (mAppSwitchDueTime < *nextWakeupTime) {
556 *nextWakeupTime = mAppSwitchDueTime;
557 }
558
559 // Ready to start a new event.
560 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700561 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700562 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 if (isAppSwitchDue) {
564 // The inbound queue is empty so the app switch key we were waiting
565 // for will never arrive. Stop waiting for it.
566 resetPendingAppSwitchLocked(false);
567 isAppSwitchDue = false;
568 }
569
570 // Synthesize a key repeat if appropriate.
571 if (mKeyRepeatState.lastKeyEntry) {
572 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
573 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
574 } else {
575 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
576 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
577 }
578 }
579 }
580
581 // Nothing to do if there is no pending event.
582 if (!mPendingEvent) {
583 return;
584 }
585 } else {
586 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700587 mPendingEvent = mInboundQueue.front();
588 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 traceInboundQueueLengthLocked();
590 }
591
592 // Poke user activity for this event.
593 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597
598 // Now we have an event to dispatch.
599 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700600 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 }
608
609 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700614 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ConfigurationChangedEntry* typedEntry =
616 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
617 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 break;
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700622 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
624 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 break;
627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100629 case EventEntry::Type::FOCUS: {
630 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
631 dispatchFocusLocked(currentTime, typedEntry);
632 done = true;
633 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
634 break;
635 }
636
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700637 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
639 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 resetPendingAppSwitchLocked(true);
642 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700643 } else if (dropReason == DropReason::NOT_DROPPED) {
644 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 }
646 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700650 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
651 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 }
653 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
654 break;
655 }
656
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700657 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700659 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
660 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700662 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
666 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 }
668 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
672
673 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
Michael Wright3a981722015-06-10 15:26:13 +0100677 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678
679 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682}
683
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700684/**
685 * Return true if the events preceding this incoming motion event should be dropped
686 * Return false otherwise (the default behaviour)
687 */
688bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700690 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691
692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
696 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700697 int32_t displayId = motionEntry.displayId;
698 int32_t x = static_cast<int32_t>(
699 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
700 int32_t y = static_cast<int32_t>(
701 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
702 sp<InputWindowHandle> touchedWindowHandle =
703 findTouchedWindowAtLocked(displayId, x, y, nullptr);
704 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 touchedWindowHandle->getApplicationToken() !=
706 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700707 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 ALOGI("Pruning input queue because user touched a different application while waiting "
709 "for %s",
710 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700711 return true;
712 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713
714 // Alternatively, maybe there's a gesture monitor that could handle this event
715 std::vector<TouchedMonitor> gestureMonitors =
716 findTouchedGestureMonitorsLocked(displayId, {});
717 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
718 sp<Connection> connection =
719 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000720 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 // This monitor could take more input. Drop all events preceding this
722 // event, so that gesture monitor could get a chance to receive the stream
723 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
724 "responsive gesture monitor that may handle the event",
725 mAwaitedFocusedApplication->getName().c_str());
726 return true;
727 }
728 }
729 }
730
731 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
732 // yet been processed by some connections, the dispatcher will wait for these motion
733 // events to be processed before dispatching the key event. This is because these motion events
734 // may cause a new window to be launched, which the user might expect to receive focus.
735 // To prevent waiting forever for such events, just send the key to the currently focused window
736 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
737 ALOGD("Received a new pointer down event, stop waiting for events to process and "
738 "just send the pending key event to the focused window.");
739 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700740 }
741 return false;
742}
743
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 bool needWake = mInboundQueue.empty();
746 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748
749 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700750 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 // Optimize app switch latency.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700754 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700756 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 mAppSwitchSawKeyDown = false;
765 needWake = true;
766 }
767 }
768 }
769 break;
770 }
771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700773 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
774 mNextUnblockedEvent = entry;
775 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700780 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
781 break;
782 }
783 case EventEntry::Type::CONFIGURATION_CHANGED:
784 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 // nothing to do
786 break;
787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 return needWake;
791}
792
793void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
794 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mRecentQueue.push_back(entry);
796 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
797 mRecentQueue.front()->release();
798 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700803 int32_t y, TouchState* touchState,
804 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700806 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
807 LOG_ALWAYS_FATAL(
808 "Must provide a valid touch state if adding portal windows or outside targets");
809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700811 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800812 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
814 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100815 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816
817 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100818 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
819 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
820 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800822 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700823 if (portalToDisplayId != ADISPLAY_ID_NONE &&
824 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800825 if (addPortalWindows) {
826 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700827 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800828 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700829 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 // Found window.
833 return windowHandle;
834 }
835 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800836
Michael Wright44753b12020-07-08 13:48:11 +0100837 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700838 touchState->addOrUpdateWindow(windowHandle,
839 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
840 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
844 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700845 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846}
847
Garfield Tane84e6f92019-08-29 17:28:41 -0700848std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700849 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000850 std::vector<TouchedMonitor> touchedMonitors;
851
852 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
853 addGestureMonitors(monitors, touchedMonitors);
854 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
855 const InputWindowInfo* windowInfo = portalWindow->getInfo();
856 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
858 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000859 }
860 return touchedMonitors;
861}
862
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 const char* reason;
865 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 reason = "inbound event was dropped because the policy consumed it";
871 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700872 case DropReason::DISABLED:
873 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 ALOGI("Dropped event because input dispatch is disabled.");
875 }
876 reason = "inbound event was dropped because input dispatch is disabled";
877 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 ALOGI("Dropped event because of pending overdue app switch.");
880 reason = "inbound event was dropped because of pending overdue app switch";
881 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 ALOGI("Dropped event because the current application is not responding and the user "
884 "has started interacting with a different application.");
885 reason = "inbound event was dropped because the current application is not responding "
886 "and the user has started interacting with a different application";
887 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700888 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 ALOGI("Dropped event because it is stale.");
890 reason = "inbound event was dropped because it is stale";
891 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700892 case DropReason::NOT_DROPPED: {
893 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700898 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700899 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
901 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700905 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
906 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
908 synthesizeCancelationEventsForAllConnectionsLocked(options);
909 } else {
910 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
911 synthesizeCancelationEventsForAllConnectionsLocked(options);
912 }
913 break;
914 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100915 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700916 case EventEntry::Type::CONFIGURATION_CHANGED:
917 case EventEntry::Type::DEVICE_RESET: {
918 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
919 break;
920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 }
922}
923
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800924static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
926 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927}
928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
930 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
931 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
932 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933}
934
935bool InputDispatcher::isAppSwitchPendingLocked() {
936 return mAppSwitchDueTime != LONG_LONG_MAX;
937}
938
939void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
940 mAppSwitchDueTime = LONG_LONG_MAX;
941
942#if DEBUG_APP_SWITCH
943 if (handled) {
944 ALOGD("App switch has arrived.");
945 } else {
946 ALOGD("App switch was abandoned.");
947 }
948#endif
949}
950
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700952 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953}
954
955bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700956 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 return false;
958 }
959
960 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700961 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700962 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700964 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965
966 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 return true;
969}
970
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700971void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
972 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973}
974
975void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700976 while (!mInboundQueue.empty()) {
977 EventEntry* entry = mInboundQueue.front();
978 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 releaseInboundEventLocked(entry);
980 }
981 traceInboundQueueLengthLocked();
982}
983
984void InputDispatcher::releasePendingEventLocked() {
985 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700987 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 }
989}
990
991void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
992 InjectionState* injectionState = entry->injectionState;
993 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
994#if DEBUG_DISPATCH_CYCLE
995 ALOGD("Injected inbound event was dropped.");
996#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800997 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
999 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001000 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002 addRecentEventLocked(entry);
1003 entry->release();
1004}
1005
1006void InputDispatcher::resetKeyRepeatLocked() {
1007 if (mKeyRepeatState.lastKeyEntry) {
1008 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001009 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011}
1012
Garfield Tane84e6f92019-08-29 17:28:41 -07001013KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1015
1016 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001017 uint32_t policyFlags = entry->policyFlags &
1018 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 if (entry->refCount == 1) {
1020 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001021 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 entry->eventTime = currentTime;
1023 entry->policyFlags = policyFlags;
1024 entry->repeatCount += 1;
1025 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001027 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001028 entry->displayId, policyFlags, entry->action, entry->flags,
1029 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
1032 mKeyRepeatState.lastKeyEntry = newEntry;
1033 entry->release();
1034
1035 entry = newEntry;
1036 }
1037 entry->syntheticRepeat = true;
1038
1039 // Increment reference count since we keep a reference to the event in
1040 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1041 entry->refCount += 1;
1042
1043 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1044 return entry;
1045}
1046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1048 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001050 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051#endif
1052
1053 // Reset key repeating in case a keyboard device was added or removed or something.
1054 resetKeyRepeatLocked();
1055
1056 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001057 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1058 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001060 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 return true;
1062}
1063
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001066 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068#endif
1069
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 options.deviceId = entry->deviceId;
1072 synthesizeCancelationEventsForAllConnectionsLocked(options);
1073 return true;
1074}
1075
Vishnu Nairad321cd2020-08-20 16:40:21 -07001076void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001077 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001078 if (mPendingEvent != nullptr) {
1079 // Move the pending event to the front of the queue. This will give the chance
1080 // for the pending event to get dispatched to the newly focused window
1081 mInboundQueue.push_front(mPendingEvent);
1082 mPendingEvent = nullptr;
1083 }
1084
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001086 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001087
1088 // This event should go to the front of the queue, but behind all other focus events
1089 // Find the last focus event, and insert right after it
1090 std::deque<EventEntry*>::reverse_iterator it =
1091 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1092 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1093
1094 // Maintain the order of focus events. Insert the entry after all other focus events.
1095 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001096}
1097
1098void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001099 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100 if (channel == nullptr) {
1101 return; // Window has gone away
1102 }
1103 InputTarget target;
1104 target.inputChannel = channel;
1105 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1106 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001107 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1108 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001109 std::string reason = std::string("reason=").append(entry->reason);
1110 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001111 dispatchEventLocked(currentTime, entry, {target});
1112}
1113
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 if (!entry->dispatchInProgress) {
1118 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1119 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1120 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1121 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001122 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 // We have seen two identical key downs in a row which indicates that the device
1124 // driver is automatically generating key repeats itself. We take note of the
1125 // repeat here, but we disable our own next key repeat timer since it is clear that
1126 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001127 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1128 // Make sure we don't get key down from a different device. If a different
1129 // device Id has same key pressed down, the new device Id will replace the
1130 // current one to hold the key repeat with repeat count reset.
1131 // In the future when got a KEY_UP on the device id, drop it and do not
1132 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1134 resetKeyRepeatLocked();
1135 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1136 } else {
1137 // Not a repeat. Save key down state in case we do see a repeat later.
1138 resetKeyRepeatLocked();
1139 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1140 }
1141 mKeyRepeatState.lastKeyEntry = entry;
1142 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001143 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1144 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1145 // The stale device releases the key, reset staleDeviceId.
1146#if DEBUG_INBOUND_EVENT_DETAILS
1147 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1148#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 resetKeyRepeatLocked();
1151 }
1152
1153 if (entry->repeatCount == 1) {
1154 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1155 } else {
1156 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1157 }
1158
1159 entry->dispatchInProgress = true;
1160
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001161 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163
1164 // Handle case where the policy asked us to try again later last time.
1165 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1166 if (currentTime < entry->interceptKeyWakeupTime) {
1167 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1168 *nextWakeupTime = entry->interceptKeyWakeupTime;
1169 }
1170 return false; // wait until next wakeup
1171 }
1172 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1173 entry->interceptKeyWakeupTime = 0;
1174 }
1175
1176 // Give the policy a chance to intercept the key.
1177 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1178 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001179 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001180 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001181 sp<IBinder> focusedWindowToken =
1182 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1183 if (focusedWindowToken != nullptr) {
1184 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001187 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 entry->refCount += 1;
1189 return false; // wait for the command to run
1190 } else {
1191 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1192 }
1193 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001194 if (*dropReason == DropReason::NOT_DROPPED) {
1195 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197 }
1198
1199 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001200 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001202 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001204 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 return true;
1206 }
1207
1208 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001209 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1213 return false;
1214 }
1215
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001216 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1218 return true;
1219 }
1220
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001221 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001222 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223
1224 // Dispatch the key.
1225 dispatchEventLocked(currentTime, entry, inputTargets);
1226 return true;
1227}
1228
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001229void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001231 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1233 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001234 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1235 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1236 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237#endif
1238}
1239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1241 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001242 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 entry->dispatchInProgress = true;
1246
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001247 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249
1250 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001251 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001253 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 return true;
1256 }
1257
1258 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1259
1260 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001261 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262
1263 bool conflictingPointerActions = false;
1264 int32_t injectionResult;
1265 if (isPointerEvent) {
1266 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001267 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001268 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 } else {
1271 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001273 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1276 return false;
1277 }
1278
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001279 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001280 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1281 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1282 return true;
1283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001285 CancelationOptions::Mode mode(isPointerEvent
1286 ? CancelationOptions::CANCEL_POINTER_EVENTS
1287 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1288 CancelationOptions options(mode, "input event injection failed");
1289 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 return true;
1291 }
1292
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001293 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001294 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001296 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001297 std::unordered_map<int32_t, TouchState>::iterator it =
1298 mTouchStatesByDisplay.find(entry->displayId);
1299 if (it != mTouchStatesByDisplay.end()) {
1300 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001301 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001302 // The event has gone through these portal windows, so we add monitoring targets of
1303 // the corresponding displays as well.
1304 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001305 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001306 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001308 }
1309 }
1310 }
1311 }
1312
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 // Dispatch the motion.
1314 if (conflictingPointerActions) {
1315 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 synthesizeCancelationEventsForAllConnectionsLocked(options);
1318 }
1319 dispatchEventLocked(currentTime, entry, inputTargets);
1320 return true;
1321}
1322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001325 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001326 ", policyFlags=0x%x, "
1327 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1328 "metaState=0x%x, buttonState=0x%x,"
1329 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1331 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1332 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 "x=%f, y=%f, pressure=%f, size=%f, "
1337 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1338 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001339 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1340 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1341 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1342 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1343 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1344 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1345 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1346 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1347 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1348 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350#endif
1351}
1352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1354 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001355 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356#if DEBUG_DISPATCH_CYCLE
1357 ALOGD("dispatchEventToCurrentInputTargets");
1358#endif
1359
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001360 updateInteractionTokensLocked(*eventEntry, inputTargets);
1361
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1363
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001364 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001366 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001367 sp<Connection> connection =
1368 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001369 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001370 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001372 if (DEBUG_FOCUS) {
1373 ALOGD("Dropping event delivery to target with channel '%s' because it "
1374 "is no longer registered with the input dispatcher.",
1375 inputTarget.inputChannel->getName().c_str());
1376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378 }
1379}
1380
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001381void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1382 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1383 // If the policy decides to close the app, we will get a channel removal event via
1384 // unregisterInputChannel, and will clean up the connection that way. We are already not
1385 // sending new pointers to the connection when it blocked, but focused events will continue to
1386 // pile up.
1387 ALOGW("Canceling events for %s because it is unresponsive",
1388 connection->inputChannel->getName().c_str());
1389 if (connection->status == Connection::STATUS_NORMAL) {
1390 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1391 "application not responding");
1392 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
1394}
1395
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001396void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001397 if (DEBUG_FOCUS) {
1398 ALOGD("Resetting ANR timeouts.");
1399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400
1401 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001402 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001403 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404}
1405
Tiger Huang721e26f2018-07-24 22:26:19 +08001406/**
1407 * Get the display id that the given event should go to. If this event specifies a valid display id,
1408 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1409 * Focused display is the display that the user most recently interacted with.
1410 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001412 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001414 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001415 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1416 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 break;
1418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001419 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1421 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 break;
1423 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001424 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001425 case EventEntry::Type::CONFIGURATION_CHANGED:
1426 case EventEntry::Type::DEVICE_RESET: {
1427 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 return ADISPLAY_ID_NONE;
1429 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001430 }
1431 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1432}
1433
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001434bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1435 const char* focusedWindowName) {
1436 if (mAnrTracker.empty()) {
1437 // already processed all events that we waited for
1438 mKeyIsWaitingForEventsTimeout = std::nullopt;
1439 return false;
1440 }
1441
1442 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1443 // Start the timer
1444 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1445 "focus to change",
1446 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001447 mKeyIsWaitingForEventsTimeout = currentTime +
1448 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1449 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001450 return true;
1451 }
1452
1453 // We still have pending events, and already started the timer
1454 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1455 return true; // Still waiting
1456 }
1457
1458 // Waited too long, and some connection still hasn't processed all motions
1459 // Just send the key to the focused window
1460 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1461 focusedWindowName);
1462 mKeyIsWaitingForEventsTimeout = std::nullopt;
1463 return false;
1464}
1465
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001467 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 std::vector<InputTarget>& inputTargets,
1469 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001470 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471
Tiger Huang721e26f2018-07-24 22:26:19 +08001472 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001473 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001474 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001475 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1476
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 // If there is no currently focused window and no focused application
1478 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001479 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1480 ALOGI("Dropping %s event because there is no focused window or focused application in "
1481 "display %" PRId32 ".",
1482 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001483 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 }
1485
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001486 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1487 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1488 // start interacting with another application via touch (app switch). This code can be removed
1489 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1490 // an app is expected to have a focused window.
1491 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1492 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1493 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001494 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1495 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1496 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001497 mAwaitedFocusedApplication = focusedApplicationHandle;
1498 ALOGW("Waiting because no window has focus but %s may eventually add a "
1499 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001500 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001501 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1502 return INPUT_EVENT_INJECTION_PENDING;
1503 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1504 // Already raised ANR. Drop the event
1505 ALOGE("Dropping %s event because there is no focused window",
1506 EventEntry::typeToString(entry.type));
1507 return INPUT_EVENT_INJECTION_FAILED;
1508 } else {
1509 // Still waiting for the focused window
1510 return INPUT_EVENT_INJECTION_PENDING;
1511 }
1512 }
1513
1514 // we have a valid, non-null focused window
1515 resetNoFocusedWindowTimeoutLocked();
1516
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001518 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001519 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 }
1521
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001522 if (focusedWindowHandle->getInfo()->paused) {
1523 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1524 return INPUT_EVENT_INJECTION_PENDING;
1525 }
1526
1527 // If the event is a key event, then we must wait for all previous events to
1528 // complete before delivering it because previous events may have the
1529 // side-effect of transferring focus to a different window and we want to
1530 // ensure that the following keys are sent to the new window.
1531 //
1532 // Suppose the user touches a button in a window then immediately presses "A".
1533 // If the button causes a pop-up window to appear then we want to ensure that
1534 // the "A" key is delivered to the new pop-up window. This is because users
1535 // often anticipate pending UI changes when typing on a keyboard.
1536 // To obtain this behavior, we must serialize key events with respect to all
1537 // prior input events.
1538 if (entry.type == EventEntry::Type::KEY) {
1539 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1540 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1541 return INPUT_EVENT_INJECTION_PENDING;
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544
1545 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001546 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1548 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549
1550 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001551 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552}
1553
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001554/**
1555 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1556 * that are currently unresponsive.
1557 */
1558std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1559 const std::vector<TouchedMonitor>& monitors) const {
1560 std::vector<TouchedMonitor> responsiveMonitors;
1561 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1562 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1563 sp<Connection> connection = getConnectionLocked(
1564 monitor.monitor.inputChannel->getConnectionToken());
1565 if (connection == nullptr) {
1566 ALOGE("Could not find connection for monitor %s",
1567 monitor.monitor.inputChannel->getName().c_str());
1568 return false;
1569 }
1570 if (!connection->responsive) {
1571 ALOGW("Unresponsive monitor %s will not get the new gesture",
1572 connection->inputChannel->getName().c_str());
1573 return false;
1574 }
1575 return true;
1576 });
1577 return responsiveMonitors;
1578}
1579
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 std::vector<InputTarget>& inputTargets,
1583 nsecs_t* nextWakeupTime,
1584 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001585 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 enum InjectionPermission {
1587 INJECTION_PERMISSION_UNKNOWN,
1588 INJECTION_PERMISSION_GRANTED,
1589 INJECTION_PERMISSION_DENIED
1590 };
1591
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 // For security reasons, we defer updating the touch state until we are sure that
1593 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001594 int32_t displayId = entry.displayId;
1595 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1597
1598 // Update the touch state as needed based on the properties of the touch event.
1599 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1600 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001601 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1602 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001604 // Copy current touch state into tempTouchState.
1605 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1606 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001607 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001608 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001609 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1610 mTouchStatesByDisplay.find(displayId);
1611 if (oldStateIt != mTouchStatesByDisplay.end()) {
1612 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001613 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001614 }
1615
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001616 bool isSplit = tempTouchState.split;
1617 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1618 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1619 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001620 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1621 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1622 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1623 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1624 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 bool wrongDevice = false;
1627 if (newGesture) {
1628 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001629 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001630 ALOGI("Dropping event because a pointer for a different device is already down "
1631 "in display %" PRId32,
1632 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001633 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1635 switchedDevice = false;
1636 wrongDevice = true;
1637 goto Failed;
1638 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001639 tempTouchState.reset();
1640 tempTouchState.down = down;
1641 tempTouchState.deviceId = entry.deviceId;
1642 tempTouchState.source = entry.source;
1643 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001645 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001646 ALOGI("Dropping move event because a pointer for a different device is already active "
1647 "in display %" PRId32,
1648 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001649 // TODO: test multiple simultaneous input streams.
1650 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1651 switchedDevice = false;
1652 wrongDevice = true;
1653 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 }
1655
1656 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1657 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1658
Garfield Tan00f511d2019-06-12 16:55:40 -07001659 int32_t x;
1660 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001662 // Always dispatch mouse events to cursor position.
1663 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001664 x = int32_t(entry.xCursorPosition);
1665 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001666 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1668 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001669 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001670 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001671 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001672 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1673 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001674
1675 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001676 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001677 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 if (newTouchedWindowHandle != nullptr &&
1681 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001682 // New window supports splitting, but we should never split mouse events.
1683 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 } else if (isSplit) {
1685 // New window does not support splitting but we have already split events.
1686 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001687 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
1689
1690 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001691 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001693 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001694 }
1695
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001696 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1697 ALOGI("Not sending touch event to %s because it is paused",
1698 newTouchedWindowHandle->getName().c_str());
1699 newTouchedWindowHandle = nullptr;
1700 }
1701
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001702 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001703 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001704 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1705 if (!isResponsive) {
1706 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001707 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1708 newTouchedWindowHandle = nullptr;
1709 }
1710 }
1711
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001712 // Drop events that can't be trusted due to occlusion
1713 if (newTouchedWindowHandle != nullptr &&
1714 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1715 TouchOcclusionInfo occlusionInfo =
1716 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
1717 // The order of the operands in the 'if' below is important because even if the feature
1718 // is not BLOCK we want isTouchTrustedLocked() to execute in order to log details to
1719 // logcat.
1720 if (!isTouchTrustedLocked(occlusionInfo) &&
1721 mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1722 ALOGW("Dropping untrusted touch event due to %s/%d",
1723 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1724 newTouchedWindowHandle = nullptr;
1725 }
1726 }
1727
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728 // Also don't send the new touch event to unresponsive gesture monitors
1729 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1730
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1732 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001733 "(%d, %d) in display %" PRId32 ".",
1734 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1736 goto Failed;
1737 }
1738
1739 if (newTouchedWindowHandle != nullptr) {
1740 // Set target flags.
1741 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1742 if (isSplit) {
1743 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001745 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1746 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1747 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1748 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1749 }
1750
1751 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001752 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1753 newHoverWindowHandle = nullptr;
1754 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001755 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001756 }
1757
1758 // Update the temporary touch state.
1759 BitSet32 pointerIds;
1760 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001762 pointerIds.markBit(pointerId);
1763 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001764 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
1766
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001767 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 } else {
1769 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1770
1771 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001772 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001773 if (DEBUG_FOCUS) {
1774 ALOGD("Dropping event because the pointer is not down or we previously "
1775 "dropped the pointer down event in display %" PRId32,
1776 displayId);
1777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1779 goto Failed;
1780 }
1781
1782 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001784 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001785 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1786 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787
1788 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001789 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001790 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1792 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001793 if (DEBUG_FOCUS) {
1794 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1795 oldTouchedWindowHandle->getName().c_str(),
1796 newTouchedWindowHandle->getName().c_str(), displayId);
1797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001799 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1800 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1801 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802
1803 // Make a slippery entrance into the new window.
1804 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1805 isSplit = true;
1806 }
1807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 int32_t targetFlags =
1809 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 if (isSplit) {
1811 targetFlags |= InputTarget::FLAG_SPLIT;
1812 }
1813 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1814 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1815 }
1816
1817 BitSet32 pointerIds;
1818 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001821 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823 }
1824 }
1825
1826 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001827 // Let the previous window know that the hover sequence is over, unless we already did it
1828 // when dispatching it as is to newTouchedWindowHandle.
1829 if (mLastHoverWindowHandle != nullptr &&
1830 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1831 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832#if DEBUG_HOVER
1833 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001834 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1837 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 }
1839
Garfield Tandf26e862020-07-01 20:18:19 -07001840 // Let the new window know that the hover sequence is starting, unless we already did it
1841 // when dispatching it as is to newTouchedWindowHandle.
1842 if (newHoverWindowHandle != nullptr &&
1843 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1844 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845#if DEBUG_HOVER
1846 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001849 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1850 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1851 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 }
1853 }
1854
1855 // Check permission to inject into all touched foreground windows and ensure there
1856 // is at least one touched foreground window.
1857 {
1858 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001859 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1861 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001862 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1864 injectionPermission = INJECTION_PERMISSION_DENIED;
1865 goto Failed;
1866 }
1867 }
1868 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001869 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001871 ALOGI("Dropping event because there is no touched foreground window in display "
1872 "%" PRId32 " or gesture monitor to receive it.",
1873 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1875 goto Failed;
1876 }
1877
1878 // Permission granted to injection into all touched foreground windows.
1879 injectionPermission = INJECTION_PERMISSION_GRANTED;
1880 }
1881
1882 // Check whether windows listening for outside touches are owned by the same UID. If it is
1883 // set the policy flag that we will not reveal coordinate information to this window.
1884 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1885 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001886 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 if (foregroundWindowHandle) {
1888 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001889 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001890 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1891 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1892 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1894 InputTarget::FLAG_ZERO_COORDS,
1895 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898 }
1899 }
1900 }
1901
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 // If this is the first pointer going down and the touched window has a wallpaper
1903 // then also add the touched wallpaper windows so they are locked in for the duration
1904 // of the touch gesture.
1905 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1906 // engine only supports touch events. We would need to add a mechanism similar
1907 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1908 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1909 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001910 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001911 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001912 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001913 getWindowHandlesLocked(displayId);
1914 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001916 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001917 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001919 .addOrUpdateWindow(windowHandle,
1920 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1921 InputTarget::
1922 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1923 InputTarget::FLAG_DISPATCH_AS_IS,
1924 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926 }
1927 }
1928 }
1929
1930 // Success! Output targets.
1931 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1932
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001933 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001938 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001939 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 }
1942
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 // Drop the outside or hover touch windows since we will not care about them
1944 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001945 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
1947Failed:
1948 // Check injection permission once and for all.
1949 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001950 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 injectionPermission = INJECTION_PERMISSION_GRANTED;
1952 } else {
1953 injectionPermission = INJECTION_PERMISSION_DENIED;
1954 }
1955 }
1956
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001957 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1958 return injectionResult;
1959 }
1960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001962 if (!wrongDevice) {
1963 if (switchedDevice) {
1964 if (DEBUG_FOCUS) {
1965 ALOGD("Conflicting pointer actions: Switched to a different device.");
1966 }
1967 *outConflictingPointerActions = true;
1968 }
1969
1970 if (isHoverAction) {
1971 // Started hovering, therefore no longer down.
1972 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001973 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001974 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1975 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 *outConflictingPointerActions = true;
1978 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001979 tempTouchState.reset();
1980 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1981 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1982 tempTouchState.deviceId = entry.deviceId;
1983 tempTouchState.source = entry.source;
1984 tempTouchState.displayId = displayId;
1985 }
1986 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1987 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1988 // All pointers up or canceled.
1989 tempTouchState.reset();
1990 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1991 // First pointer went down.
1992 if (oldState && oldState->down) {
1993 if (DEBUG_FOCUS) {
1994 ALOGD("Conflicting pointer actions: Down received while already down.");
1995 }
1996 *outConflictingPointerActions = true;
1997 }
1998 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1999 // One pointer went up.
2000 if (isSplit) {
2001 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2002 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002004 for (size_t i = 0; i < tempTouchState.windows.size();) {
2005 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2006 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2007 touchedWindow.pointerIds.clearBit(pointerId);
2008 if (touchedWindow.pointerIds.isEmpty()) {
2009 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2010 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002013 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002015 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002016 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002017
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002018 // Save changes unless the action was scroll in which case the temporary touch
2019 // state was only valid for this one action.
2020 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2021 if (tempTouchState.displayId >= 0) {
2022 mTouchStatesByDisplay[displayId] = tempTouchState;
2023 } else {
2024 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002028 // Update hover state.
2029 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 }
2031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 return injectionResult;
2033}
2034
2035void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 int32_t targetFlags, BitSet32 pointerIds,
2037 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002038 std::vector<InputTarget>::iterator it =
2039 std::find_if(inputTargets.begin(), inputTargets.end(),
2040 [&windowHandle](const InputTarget& inputTarget) {
2041 return inputTarget.inputChannel->getConnectionToken() ==
2042 windowHandle->getToken();
2043 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002044
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002045 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002046
2047 if (it == inputTargets.end()) {
2048 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002049 std::shared_ptr<InputChannel> inputChannel =
2050 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002051 if (inputChannel == nullptr) {
2052 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2053 return;
2054 }
2055 inputTarget.inputChannel = inputChannel;
2056 inputTarget.flags = targetFlags;
2057 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2058 inputTargets.push_back(inputTarget);
2059 it = inputTargets.end() - 1;
2060 }
2061
2062 ALOG_ASSERT(it->flags == targetFlags);
2063 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2064
chaviw1ff3d1e2020-07-01 15:53:47 -07002065 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066}
2067
Michael Wright3dd60e22019-03-27 22:06:44 +00002068void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 int32_t displayId, float xOffset,
2070 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002071 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2072 mGlobalMonitorsByDisplay.find(displayId);
2073
2074 if (it != mGlobalMonitorsByDisplay.end()) {
2075 const std::vector<Monitor>& monitors = it->second;
2076 for (const Monitor& monitor : monitors) {
2077 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080}
2081
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002082void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2083 float yOffset,
2084 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 InputTarget target;
2086 target.inputChannel = monitor.inputChannel;
2087 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002088 ui::Transform t;
2089 t.set(xOffset, yOffset);
2090 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 inputTargets.push_back(target);
2092}
2093
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 const InjectionState* injectionState) {
2096 if (injectionState &&
2097 (windowHandle == nullptr ||
2098 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2099 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002100 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 "owned by uid %d",
2103 injectionState->injectorPid, injectionState->injectorUid,
2104 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 } else {
2106 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
2109 return false;
2110 }
2111 return true;
2112}
2113
Robert Carrc9bf1d32020-04-13 17:21:08 -07002114/**
2115 * Indicate whether one window handle should be considered as obscuring
2116 * another window handle. We only check a few preconditions. Actually
2117 * checking the bounds is left to the caller.
2118 */
2119static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2120 const sp<InputWindowHandle>& otherHandle) {
2121 // Compare by token so cloned layers aren't counted
2122 if (haveSameToken(windowHandle, otherHandle)) {
2123 return false;
2124 }
2125 auto info = windowHandle->getInfo();
2126 auto otherInfo = otherHandle->getInfo();
2127 if (!otherInfo->visible) {
2128 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002129 } else if (info->ownerPid == otherInfo->ownerPid) {
2130 // If ownerPid is the same we don't generate occlusion events as there
2131 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002132 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002133 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002134 return false;
2135 } else if (otherInfo->displayId != info->displayId) {
2136 return false;
2137 }
2138 return true;
2139}
2140
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002141/**
2142 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2143 * untrusted, one should check:
2144 *
2145 * 1. If result.hasBlockingOcclusion is true.
2146 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2147 * BLOCK_UNTRUSTED.
2148 *
2149 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2150 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2151 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2152 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2153 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2154 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2155 *
2156 * If neither of those is true, then it means the touch can be allowed.
2157 */
2158InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2159 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2160 int32_t displayId = windowHandle->getInfo()->displayId;
2161 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2162 TouchOcclusionInfo info;
2163 info.hasBlockingOcclusion = false;
2164 info.obscuringOpacity = 0;
2165 info.obscuringUid = -1;
2166 std::map<int32_t, float> opacityByUid;
2167 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2168 if (windowHandle == otherHandle) {
2169 break; // All future windows are below us. Exit early.
2170 }
2171 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2172 if (canBeObscuredBy(windowHandle, otherHandle) &&
2173 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2174 otherInfo->frameContainsPoint(x, y)) {
2175 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2176 // we perform the checks below to see if the touch can be propagated or not based on the
2177 // window's touch occlusion mode
2178 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2179 info.hasBlockingOcclusion = true;
2180 info.obscuringUid = otherInfo->ownerUid;
2181 info.obscuringPackage = otherInfo->packageName;
2182 break;
2183 }
2184 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2185 uint32_t uid = otherInfo->ownerUid;
2186 float opacity =
2187 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2188 // Given windows A and B:
2189 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2190 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2191 opacityByUid[uid] = opacity;
2192 if (opacity > info.obscuringOpacity) {
2193 info.obscuringOpacity = opacity;
2194 info.obscuringUid = uid;
2195 info.obscuringPackage = otherInfo->packageName;
2196 }
2197 }
2198 }
2199 }
2200 return info;
2201}
2202
2203bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2204 if (occlusionInfo.hasBlockingOcclusion) {
2205 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2206 occlusionInfo.obscuringUid);
2207 return false;
2208 }
2209 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2210 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2211 "%.2f, maximum allowed = %.2f)",
2212 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2213 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2214 return false;
2215 }
2216 return true;
2217}
2218
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2220 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002222 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002223 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002224 if (windowHandle == otherHandle) {
2225 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002228 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002229 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 return true;
2231 }
2232 }
2233 return false;
2234}
2235
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002236bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2237 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002238 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002239 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002240 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002241 if (windowHandle == otherHandle) {
2242 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002243 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002244 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002245 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002246 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002247 return true;
2248 }
2249 }
2250 return false;
2251}
2252
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002253std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002254 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002256 if (applicationHandle != nullptr) {
2257 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002258 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 } else {
2260 return applicationHandle->getName();
2261 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002262 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002263 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002265 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267}
2268
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002269void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002270 if (eventEntry.type == EventEntry::Type::FOCUS) {
2271 // Focus events are passed to apps, but do not represent user activity.
2272 return;
2273 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002274 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002275 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002276 if (focusedWindowHandle != nullptr) {
2277 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002278 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002280 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281#endif
2282 return;
2283 }
2284 }
2285
2286 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002287 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002288 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002289 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2290 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 return;
2292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002294 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 eventType = USER_ACTIVITY_EVENT_TOUCH;
2296 }
2297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002299 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002300 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2301 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 return;
2303 }
2304 eventType = USER_ACTIVITY_EVENT_BUTTON;
2305 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002307 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002308 case EventEntry::Type::CONFIGURATION_CHANGED:
2309 case EventEntry::Type::DEVICE_RESET: {
2310 LOG_ALWAYS_FATAL("%s events are not user activity",
2311 EventEntry::typeToString(eventEntry.type));
2312 break;
2313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002316 std::unique_ptr<CommandEntry> commandEntry =
2317 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002318 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002320 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321}
2322
2323void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 const sp<Connection>& connection,
2325 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002326 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002327 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002329 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002330 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 ATRACE_NAME(message.c_str());
2332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#if DEBUG_DISPATCH_CYCLE
2334 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002335 "globalScaleFactor=%f, pointerIds=0x%x %s",
2336 connection->getInputChannelName().c_str(), inputTarget.flags,
2337 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2338 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339#endif
2340
2341 // Skip this event if the connection status is not normal.
2342 // We don't want to enqueue additional outbound events if the connection is broken.
2343 if (connection->status != Connection::STATUS_NORMAL) {
2344#if DEBUG_DISPATCH_CYCLE
2345 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347#endif
2348 return;
2349 }
2350
2351 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002352 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2353 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2354 "Entry type %s should not have FLAG_SPLIT",
2355 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002357 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002358 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002360 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 if (!splitMotionEntry) {
2362 return; // split event was dropped
2363 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002364 if (DEBUG_FOCUS) {
2365 ALOGD("channel '%s' ~ Split motion event.",
2366 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002367 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002368 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 splitMotionEntry->release();
2371 return;
2372 }
2373 }
2374
2375 // Not splitting. Enqueue dispatch entries for the event as is.
2376 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2377}
2378
2379void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 const sp<Connection>& connection,
2381 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002382 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002385 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002386 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002387 ATRACE_NAME(message.c_str());
2388 }
2389
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002390 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
2392 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002393 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002395 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002396 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002397 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002399 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002400 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002401 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002403 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405
2406 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002407 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 startDispatchCycleLocked(currentTime, connection);
2409 }
2410}
2411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002412void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2413 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002414 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2418 connection->getInputChannelName().c_str(),
2419 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002420 ATRACE_NAME(message.c_str());
2421 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002422 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 if (!(inputTargetFlags & dispatchMode)) {
2424 return;
2425 }
2426 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2427
2428 // This is a new event.
2429 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002430 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002433 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2434 // different EventEntry than what was passed in.
2435 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002437 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002438 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002440 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002441 dispatchEntry->resolvedAction = keyEntry.action;
2442 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002444 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2445 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2448 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450 return; // skip the inconsistent event
2451 }
2452 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002455 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002456 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002457 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2458 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2459 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2460 static_cast<int32_t>(IdGenerator::Source::OTHER);
2461 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002462 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2463 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2464 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2465 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2466 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2467 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2468 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2469 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2470 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2471 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2472 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002473 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002474 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 }
2476 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002477 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2478 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002480 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2481 "event",
2482 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002487 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2489 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2490 }
2491 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2492 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002495 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2496 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2499 "event",
2500 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 return; // skip the inconsistent event
2503 }
2504
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002505 dispatchEntry->resolvedEventId =
2506 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2507 ? mIdGenerator.nextId()
2508 : motionEntry.id;
2509 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2510 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2511 ") to MotionEvent(id=0x%" PRIx32 ").",
2512 motionEntry.id, dispatchEntry->resolvedEventId);
2513 ATRACE_NAME(message.c_str());
2514 }
2515
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002516 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002517 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518
2519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002521 case EventEntry::Type::FOCUS: {
2522 break;
2523 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002524 case EventEntry::Type::CONFIGURATION_CHANGED:
2525 case EventEntry::Type::DEVICE_RESET: {
2526 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002527 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002528 break;
2529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531
2532 // Remember that we are waiting for this dispatch to complete.
2533 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002534 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536
2537 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002538 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002539 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002540}
2541
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002542/**
2543 * This function is purely for debugging. It helps us understand where the user interaction
2544 * was taking place. For example, if user is touching launcher, we will see a log that user
2545 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2546 * We will see both launcher and wallpaper in that list.
2547 * Once the interaction with a particular set of connections starts, no new logs will be printed
2548 * until the set of interacted connections changes.
2549 *
2550 * The following items are skipped, to reduce the logspam:
2551 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2552 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2553 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2554 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2555 * Both of those ACTION_UP events would not be logged
2556 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2557 * will not be logged. This is omitted to reduce the amount of data printed.
2558 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2559 * gesture monitor is the only connection receiving the remainder of the gesture.
2560 */
2561void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2562 const std::vector<InputTarget>& targets) {
2563 // Skip ACTION_UP events, and all events other than keys and motions
2564 if (entry.type == EventEntry::Type::KEY) {
2565 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2566 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2567 return;
2568 }
2569 } else if (entry.type == EventEntry::Type::MOTION) {
2570 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2571 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2572 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2573 return;
2574 }
2575 } else {
2576 return; // Not a key or a motion
2577 }
2578
2579 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2580 std::vector<sp<Connection>> newConnections;
2581 for (const InputTarget& target : targets) {
2582 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2583 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2584 continue; // Skip windows that receive ACTION_OUTSIDE
2585 }
2586
2587 sp<IBinder> token = target.inputChannel->getConnectionToken();
2588 sp<Connection> connection = getConnectionLocked(token);
2589 if (connection == nullptr || connection->monitor) {
2590 continue; // We only need to keep track of the non-monitor connections.
2591 }
2592 newConnectionTokens.insert(std::move(token));
2593 newConnections.emplace_back(connection);
2594 }
2595 if (newConnectionTokens == mInteractionConnectionTokens) {
2596 return; // no change
2597 }
2598 mInteractionConnectionTokens = newConnectionTokens;
2599
2600 std::string windowList;
2601 for (const sp<Connection>& connection : newConnections) {
2602 windowList += connection->getWindowName() + ", ";
2603 }
2604 std::string message = "Interaction with windows: " + windowList;
2605 if (windowList.empty()) {
2606 message += "<none>";
2607 }
2608 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2609}
2610
chaviwfd6d3512019-03-25 13:23:49 -07002611void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002612 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002613 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002614 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2615 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002616 return;
2617 }
2618
Vishnu Nairad321cd2020-08-20 16:40:21 -07002619 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2620 if (focusedToken == token) {
2621 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002622 return;
2623 }
2624
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002625 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2626 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002627 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002628 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629}
2630
2631void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002632 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002633 if (ATRACE_ENABLED()) {
2634 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002636 ATRACE_NAME(message.c_str());
2637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002639 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640#endif
2641
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002642 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2643 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002645 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002646 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002647 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648
2649 // Publish the event.
2650 status_t status;
2651 EventEntry* eventEntry = dispatchEntry->eventEntry;
2652 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002653 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002654 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2655 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002658 status =
2659 connection->inputPublisher
2660 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2661 keyEntry->deviceId, keyEntry->source,
2662 keyEntry->displayId, std::move(hmac),
2663 dispatchEntry->resolvedAction,
2664 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2665 keyEntry->scanCode, keyEntry->metaState,
2666 keyEntry->repeatCount, keyEntry->downTime,
2667 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 }
2670
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002671 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002672 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 PointerCoords scaledCoords[MAX_POINTERS];
2675 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2676
chaviw82357092020-01-28 13:13:06 -08002677 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002678 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2679 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2680 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002681 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2683 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002684 // Don't apply window scale here since we don't want scale to affect raw
2685 // coordinates. The scale will be sent back to the client and applied
2686 // later when requesting relative coordinates.
2687 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2688 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 }
2690 usingCoords = scaledCoords;
2691 }
2692 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 // We don't want the dispatch target to know.
2694 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2695 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2696 scaledCoords[i].clear();
2697 }
2698 usingCoords = scaledCoords;
2699 }
2700 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002701
2702 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703
2704 // Publish the motion event.
2705 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002706 .publishMotionEvent(dispatchEntry->seq,
2707 dispatchEntry->resolvedEventId,
2708 motionEntry->deviceId, motionEntry->source,
2709 motionEntry->displayId, std::move(hmac),
2710 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 motionEntry->actionButton,
2712 dispatchEntry->resolvedFlags,
2713 motionEntry->edgeFlags, motionEntry->metaState,
2714 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002715 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002716 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002717 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 motionEntry->yPrecision,
2719 motionEntry->xCursorPosition,
2720 motionEntry->yCursorPosition,
2721 motionEntry->downTime, motionEntry->eventTime,
2722 motionEntry->pointerCount,
2723 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002724 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 break;
2726 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002727 case EventEntry::Type::FOCUS: {
2728 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2729 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002730 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002731 focusEntry->hasFocus,
2732 mInTouchMode);
2733 break;
2734 }
2735
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002736 case EventEntry::Type::CONFIGURATION_CHANGED:
2737 case EventEntry::Type::DEVICE_RESET: {
2738 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2739 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
2743
2744 // Check the result.
2745 if (status) {
2746 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002747 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 "This is unexpected because the wait queue is empty, so the pipe "
2750 "should be empty and we shouldn't have any problems writing an "
2751 "event to it, status=%d",
2752 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2754 } else {
2755 // Pipe is full and we are waiting for the app to finish process some events
2756 // before sending more events to it.
2757#if DEBUG_DISPATCH_CYCLE
2758 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 "waiting for the application to catch up",
2760 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763 } else {
2764 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 "status=%d",
2766 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2768 }
2769 return;
2770 }
2771
2772 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002773 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2774 connection->outboundQueue.end(),
2775 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002776 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002777 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002778 if (connection->responsive) {
2779 mAnrTracker.insert(dispatchEntry->timeoutTime,
2780 connection->inputChannel->getConnectionToken());
2781 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002782 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
2784}
2785
chaviw09c8d2d2020-08-24 15:48:26 -07002786std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2787 size_t size;
2788 switch (event.type) {
2789 case VerifiedInputEvent::Type::KEY: {
2790 size = sizeof(VerifiedKeyEvent);
2791 break;
2792 }
2793 case VerifiedInputEvent::Type::MOTION: {
2794 size = sizeof(VerifiedMotionEvent);
2795 break;
2796 }
2797 }
2798 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2799 return mHmacKeyManager.sign(start, size);
2800}
2801
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002802const std::array<uint8_t, 32> InputDispatcher::getSignature(
2803 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2804 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2805 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2806 // Only sign events up and down events as the purely move events
2807 // are tied to their up/down counterparts so signing would be redundant.
2808 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2809 verifiedEvent.actionMasked = actionMasked;
2810 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002811 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002812 }
2813 return INVALID_HMAC;
2814}
2815
2816const std::array<uint8_t, 32> InputDispatcher::getSignature(
2817 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2818 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2819 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2820 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002821 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002822}
2823
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 const sp<Connection>& connection, uint32_t seq,
2826 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827#if DEBUG_DISPATCH_CYCLE
2828 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830#endif
2831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 if (connection->status == Connection::STATUS_BROKEN ||
2833 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 return;
2835 }
2836
2837 // Notify other system components and prepare to start the next dispatch cycle.
2838 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2839}
2840
2841void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 const sp<Connection>& connection,
2843 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844#if DEBUG_DISPATCH_CYCLE
2845 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847#endif
2848
2849 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002850 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002851 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002852 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002853 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854
2855 // The connection appears to be unrecoverably broken.
2856 // Ignore already broken or zombie connections.
2857 if (connection->status == Connection::STATUS_NORMAL) {
2858 connection->status = Connection::STATUS_BROKEN;
2859
2860 if (notify) {
2861 // Notify other system components.
2862 onDispatchCycleBrokenLocked(currentTime, connection);
2863 }
2864 }
2865}
2866
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002867void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2868 while (!queue.empty()) {
2869 DispatchEntry* dispatchEntry = queue.front();
2870 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002871 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 }
2873}
2874
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002875void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002877 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 }
2879 delete dispatchEntry;
2880}
2881
2882int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2883 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2884
2885 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002886 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002888 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 "fd=%d, events=0x%x",
2891 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 return 0; // remove the callback
2893 }
2894
2895 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002896 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2898 if (!(events & ALOOPER_EVENT_INPUT)) {
2899 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 "events=0x%x",
2901 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 return 1;
2903 }
2904
2905 nsecs_t currentTime = now();
2906 bool gotOne = false;
2907 status_t status;
2908 for (;;) {
2909 uint32_t seq;
2910 bool handled;
2911 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2912 if (status) {
2913 break;
2914 }
2915 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2916 gotOne = true;
2917 }
2918 if (gotOne) {
2919 d->runCommandsLockedInterruptible();
2920 if (status == WOULD_BLOCK) {
2921 return 1;
2922 }
2923 }
2924
2925 notify = status != DEAD_OBJECT || !connection->monitor;
2926 if (notify) {
2927 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
2930 } else {
2931 // Monitor channels are never explicitly unregistered.
2932 // We do it automatically when the remote endpoint is closed so don't warn
2933 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002934 const bool stillHaveWindowHandle =
2935 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2936 nullptr;
2937 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 if (notify) {
2939 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 "events=0x%x",
2941 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 }
2943 }
2944
Garfield Tan15601662020-09-22 15:32:38 -07002945 // Remove the channel.
2946 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949}
2950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002953 for (const auto& pair : mConnectionsByFd) {
2954 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 }
2956}
2957
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002959 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002960 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2961 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2962}
2963
2964void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2965 const CancelationOptions& options,
2966 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2967 for (const auto& it : monitorsByDisplay) {
2968 const std::vector<Monitor>& monitors = it.second;
2969 for (const Monitor& monitor : monitors) {
2970 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002971 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002972 }
2973}
2974
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002976 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002977 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002978 if (connection == nullptr) {
2979 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002981
2982 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983}
2984
2985void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2986 const sp<Connection>& connection, const CancelationOptions& options) {
2987 if (connection->status == Connection::STATUS_BROKEN) {
2988 return;
2989 }
2990
2991 nsecs_t currentTime = now();
2992
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002993 std::vector<EventEntry*> cancelationEvents =
2994 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002996 if (cancelationEvents.empty()) {
2997 return;
2998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003000 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3001 "with reality: %s, mode=%d.",
3002 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3003 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003005
3006 InputTarget target;
3007 sp<InputWindowHandle> windowHandle =
3008 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3009 if (windowHandle != nullptr) {
3010 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003011 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003012 target.globalScaleFactor = windowInfo->globalScaleFactor;
3013 }
3014 target.inputChannel = connection->inputChannel;
3015 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3016
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003017 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3018 EventEntry* cancelationEventEntry = cancelationEvents[i];
3019 switch (cancelationEventEntry->type) {
3020 case EventEntry::Type::KEY: {
3021 logOutboundKeyDetails("cancel - ",
3022 static_cast<const KeyEntry&>(*cancelationEventEntry));
3023 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003025 case EventEntry::Type::MOTION: {
3026 logOutboundMotionDetails("cancel - ",
3027 static_cast<const MotionEntry&>(*cancelationEventEntry));
3028 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003030 case EventEntry::Type::FOCUS: {
3031 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3032 break;
3033 }
3034 case EventEntry::Type::CONFIGURATION_CHANGED:
3035 case EventEntry::Type::DEVICE_RESET: {
3036 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3037 EventEntry::typeToString(cancelationEventEntry->type));
3038 break;
3039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 }
3041
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003042 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3043 target, InputTarget::FLAG_DISPATCH_AS_IS);
3044
3045 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003047
3048 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049}
3050
Svet Ganov5d3bc372020-01-26 23:11:07 -08003051void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3052 const sp<Connection>& connection) {
3053 if (connection->status == Connection::STATUS_BROKEN) {
3054 return;
3055 }
3056
3057 nsecs_t currentTime = now();
3058
3059 std::vector<EventEntry*> downEvents =
3060 connection->inputState.synthesizePointerDownEvents(currentTime);
3061
3062 if (downEvents.empty()) {
3063 return;
3064 }
3065
3066#if DEBUG_OUTBOUND_EVENT_DETAILS
3067 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3068 connection->getInputChannelName().c_str(), downEvents.size());
3069#endif
3070
3071 InputTarget target;
3072 sp<InputWindowHandle> windowHandle =
3073 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3074 if (windowHandle != nullptr) {
3075 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003076 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003077 target.globalScaleFactor = windowInfo->globalScaleFactor;
3078 }
3079 target.inputChannel = connection->inputChannel;
3080 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3081
3082 for (EventEntry* downEventEntry : downEvents) {
3083 switch (downEventEntry->type) {
3084 case EventEntry::Type::MOTION: {
3085 logOutboundMotionDetails("down - ",
3086 static_cast<const MotionEntry&>(*downEventEntry));
3087 break;
3088 }
3089
3090 case EventEntry::Type::KEY:
3091 case EventEntry::Type::FOCUS:
3092 case EventEntry::Type::CONFIGURATION_CHANGED:
3093 case EventEntry::Type::DEVICE_RESET: {
3094 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3095 EventEntry::typeToString(downEventEntry->type));
3096 break;
3097 }
3098 }
3099
3100 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3101 target, InputTarget::FLAG_DISPATCH_AS_IS);
3102
3103 downEventEntry->release();
3104 }
3105
3106 startDispatchCycleLocked(currentTime, connection);
3107}
3108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003109MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003110 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 ALOG_ASSERT(pointerIds.value != 0);
3112
3113 uint32_t splitPointerIndexMap[MAX_POINTERS];
3114 PointerProperties splitPointerProperties[MAX_POINTERS];
3115 PointerCoords splitPointerCoords[MAX_POINTERS];
3116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003117 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 uint32_t splitPointerCount = 0;
3119
3120 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003123 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 uint32_t pointerId = uint32_t(pointerProperties.id);
3125 if (pointerIds.hasBit(pointerId)) {
3126 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3127 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3128 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003129 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 splitPointerCount += 1;
3131 }
3132 }
3133
3134 if (splitPointerCount != pointerIds.count()) {
3135 // This is bad. We are missing some of the pointers that we expected to deliver.
3136 // Most likely this indicates that we received an ACTION_MOVE events that has
3137 // different pointer ids than we expected based on the previous ACTION_DOWN
3138 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3139 // in this way.
3140 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 "we expected there to be %d pointers. This probably means we received "
3142 "a broken sequence of pointer ids from the input device.",
3143 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
3146
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3150 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3152 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003153 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 uint32_t pointerId = uint32_t(pointerProperties.id);
3155 if (pointerIds.hasBit(pointerId)) {
3156 if (pointerIds.count() == 1) {
3157 // The first/last pointer went down/up.
3158 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 ? AMOTION_EVENT_ACTION_DOWN
3160 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 } else {
3162 // A secondary pointer went down/up.
3163 uint32_t splitPointerIndex = 0;
3164 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3165 splitPointerIndex += 1;
3166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 action = maskedAction |
3168 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
3170 } else {
3171 // An unrelated pointer changed.
3172 action = AMOTION_EVENT_ACTION_MOVE;
3173 }
3174 }
3175
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003176 int32_t newId = mIdGenerator.nextId();
3177 if (ATRACE_ENABLED()) {
3178 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3179 ") to MotionEvent(id=0x%" PRIx32 ").",
3180 originalMotionEntry.id, newId);
3181 ATRACE_NAME(message.c_str());
3182 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003183 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003184 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3185 originalMotionEntry.source, originalMotionEntry.displayId,
3186 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003187 originalMotionEntry.actionButton, originalMotionEntry.flags,
3188 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3189 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3190 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3191 originalMotionEntry.xCursorPosition,
3192 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003193 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003195 if (originalMotionEntry.injectionState) {
3196 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 splitMotionEntry->injectionState->refCount += 1;
3198 }
3199
3200 return splitMotionEntry;
3201}
3202
3203void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3204#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003205 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206#endif
3207
3208 bool needWake;
3209 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003210 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
Prabir Pradhan42611e02018-11-27 14:04:02 -08003212 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003213 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 needWake = enqueueInboundEventLocked(newEntry);
3215 } // release lock
3216
3217 if (needWake) {
3218 mLooper->wake();
3219 }
3220}
3221
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003222/**
3223 * If one of the meta shortcuts is detected, process them here:
3224 * Meta + Backspace -> generate BACK
3225 * Meta + Enter -> generate HOME
3226 * This will potentially overwrite keyCode and metaState.
3227 */
3228void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003230 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3231 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3232 if (keyCode == AKEYCODE_DEL) {
3233 newKeyCode = AKEYCODE_BACK;
3234 } else if (keyCode == AKEYCODE_ENTER) {
3235 newKeyCode = AKEYCODE_HOME;
3236 }
3237 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003238 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003239 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003240 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003241 keyCode = newKeyCode;
3242 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3243 }
3244 } else if (action == AKEY_EVENT_ACTION_UP) {
3245 // In order to maintain a consistent stream of up and down events, check to see if the key
3246 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3247 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003248 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003249 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003250 auto replacementIt = mReplacedKeys.find(replacement);
3251 if (replacementIt != mReplacedKeys.end()) {
3252 keyCode = replacementIt->second;
3253 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003254 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3255 }
3256 }
3257}
3258
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3260#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3262 "policyFlags=0x%x, action=0x%x, "
3263 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3264 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3265 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3266 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267#endif
3268 if (!validateKeyEvent(args->action)) {
3269 return;
3270 }
3271
3272 uint32_t policyFlags = args->policyFlags;
3273 int32_t flags = args->flags;
3274 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003275 // InputDispatcher tracks and generates key repeats on behalf of
3276 // whatever notifies it, so repeatCount should always be set to 0
3277 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3279 policyFlags |= POLICY_FLAG_VIRTUAL;
3280 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 if (policyFlags & POLICY_FLAG_FUNCTION) {
3283 metaState |= AMETA_FUNCTION_ON;
3284 }
3285
3286 policyFlags |= POLICY_FLAG_TRUSTED;
3287
Michael Wright78f24442014-08-06 15:55:28 -07003288 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003289 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003290
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003292 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003293 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3294 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
Michael Wright2b3c3302018-03-02 17:19:13 +00003296 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003298 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3299 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 bool needWake;
3304 { // acquire lock
3305 mLock.lock();
3306
3307 if (shouldSendKeyToInputFilterLocked(args)) {
3308 mLock.unlock();
3309
3310 policyFlags |= POLICY_FLAG_FILTERED;
3311 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3312 return; // event was consumed by the filter
3313 }
3314
3315 mLock.lock();
3316 }
3317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003319 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 args->displayId, policyFlags, args->action, flags, keyCode,
3321 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
3323 needWake = enqueueInboundEventLocked(newEntry);
3324 mLock.unlock();
3325 } // release lock
3326
3327 if (needWake) {
3328 mLooper->wake();
3329 }
3330}
3331
3332bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3333 return mInputFilterEnabled;
3334}
3335
3336void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3337#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003338 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3339 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003340 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3341 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003342 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003343 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3344 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3345 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3346 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 for (uint32_t i = 0; i < args->pointerCount; i++) {
3348 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 "x=%f, y=%f, pressure=%f, size=%f, "
3350 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3351 "orientation=%f",
3352 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3353 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3354 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3355 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3356 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3357 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3358 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3359 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3360 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3361 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 }
3363#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3365 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 return;
3367 }
3368
3369 uint32_t policyFlags = args->policyFlags;
3370 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003371
3372 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003373 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003374 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3375 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378
3379 bool needWake;
3380 { // acquire lock
3381 mLock.lock();
3382
3383 if (shouldSendMotionToInputFilterLocked(args)) {
3384 mLock.unlock();
3385
3386 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003387 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003388 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3389 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003390 args->metaState, args->buttonState, args->classification, transform,
3391 args->xPrecision, args->yPrecision, args->xCursorPosition,
3392 args->yCursorPosition, args->downTime, args->eventTime,
3393 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394
3395 policyFlags |= POLICY_FLAG_FILTERED;
3396 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3397 return; // event was consumed by the filter
3398 }
3399
3400 mLock.lock();
3401 }
3402
3403 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003404 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003405 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003406 args->displayId, policyFlags, args->action, args->actionButton,
3407 args->flags, args->metaState, args->buttonState,
3408 args->classification, args->edgeFlags, args->xPrecision,
3409 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3410 args->downTime, args->pointerCount, args->pointerProperties,
3411 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
3413 needWake = enqueueInboundEventLocked(newEntry);
3414 mLock.unlock();
3415 } // release lock
3416
3417 if (needWake) {
3418 mLooper->wake();
3419 }
3420}
3421
3422bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003423 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424}
3425
3426void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3427#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003428 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429 "switchMask=0x%08x",
3430 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431#endif
3432
3433 uint32_t policyFlags = args->policyFlags;
3434 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436}
3437
3438void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3439#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003440 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3441 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442#endif
3443
3444 bool needWake;
3445 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003446 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447
Prabir Pradhan42611e02018-11-27 14:04:02 -08003448 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003449 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 needWake = enqueueInboundEventLocked(newEntry);
3451 } // release lock
3452
3453 if (needWake) {
3454 mLooper->wake();
3455 }
3456}
3457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3459 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003460 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461#if DEBUG_INBOUND_EVENT_DETAILS
3462 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003463 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3464 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003466 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
3468 policyFlags |= POLICY_FLAG_INJECTED;
3469 if (hasInjectionPermission(injectorPid, injectorUid)) {
3470 policyFlags |= POLICY_FLAG_TRUSTED;
3471 }
3472
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003473 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003475 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003476 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3477 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003478 if (!validateKeyEvent(action)) {
3479 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003482 int32_t flags = incomingKey.getFlags();
3483 int32_t keyCode = incomingKey.getKeyCode();
3484 int32_t metaState = incomingKey.getMetaState();
3485 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003486 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003487 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003488 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003489 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3490 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3491 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003493 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3494 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003495 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003496
3497 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3498 android::base::Timer t;
3499 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3500 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3501 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3502 std::to_string(t.duration().count()).c_str());
3503 }
3504 }
3505
3506 mLock.lock();
3507 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003508 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3509 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003510 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3511 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003512 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003513 injectedEntries.push(injectedEntry);
3514 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517 case AINPUT_EVENT_TYPE_MOTION: {
3518 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3519 int32_t action = motionEvent->getAction();
3520 size_t pointerCount = motionEvent->getPointerCount();
3521 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3522 int32_t actionButton = motionEvent->getActionButton();
3523 int32_t displayId = motionEvent->getDisplayId();
3524 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3525 return INPUT_EVENT_INJECTION_FAILED;
3526 }
3527
3528 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3529 nsecs_t eventTime = motionEvent->getEventTime();
3530 android::base::Timer t;
3531 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3532 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3533 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3534 std::to_string(t.duration().count()).c_str());
3535 }
3536 }
3537
3538 mLock.lock();
3539 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3540 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3541 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003542 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3543 motionEvent->getSource(), motionEvent->getDisplayId(),
3544 policyFlags, action, actionButton, motionEvent->getFlags(),
3545 motionEvent->getMetaState(), motionEvent->getButtonState(),
3546 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3547 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003548 motionEvent->getRawXCursorPosition(),
3549 motionEvent->getRawYCursorPosition(),
3550 motionEvent->getDownTime(), uint32_t(pointerCount),
3551 pointerProperties, samplePointerCoords,
3552 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003553 injectedEntries.push(injectedEntry);
3554 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3555 sampleEventTimes += 1;
3556 samplePointerCoords += pointerCount;
3557 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003558 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003559 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 motionEvent->getDisplayId(), policyFlags, action,
3561 actionButton, motionEvent->getFlags(),
3562 motionEvent->getMetaState(), motionEvent->getButtonState(),
3563 motionEvent->getClassification(),
3564 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3565 motionEvent->getYPrecision(),
3566 motionEvent->getRawXCursorPosition(),
3567 motionEvent->getRawYCursorPosition(),
3568 motionEvent->getDownTime(), uint32_t(pointerCount),
3569 pointerProperties, samplePointerCoords,
3570 motionEvent->getXOffset(), motionEvent->getYOffset());
3571 injectedEntries.push(nextInjectedEntry);
3572 }
3573 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003577 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580
3581 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3582 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3583 injectionState->injectionIsAsync = true;
3584 }
3585
3586 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003587 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
3589 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003590 while (!injectedEntries.empty()) {
3591 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3592 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 }
3594
3595 mLock.unlock();
3596
3597 if (needWake) {
3598 mLooper->wake();
3599 }
3600
3601 int32_t injectionResult;
3602 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003603 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
3605 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3606 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3607 } else {
3608 for (;;) {
3609 injectionResult = injectionState->injectionResult;
3610 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3611 break;
3612 }
3613
3614 nsecs_t remainingTimeout = endTime - now();
3615 if (remainingTimeout <= 0) {
3616#if DEBUG_INJECTION
3617 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619#endif
3620 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3621 break;
3622 }
3623
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003624 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3628 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 while (injectionState->pendingForegroundDispatches != 0) {
3630#if DEBUG_INJECTION
3631 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003632 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633#endif
3634 nsecs_t remainingTimeout = endTime - now();
3635 if (remainingTimeout <= 0) {
3636#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3638 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639#endif
3640 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3641 break;
3642 }
3643
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003644 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646 }
3647 }
3648
3649 injectionState->release();
3650 } // release lock
3651
3652#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003653 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003654 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655#endif
3656
3657 return injectionResult;
3658}
3659
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003660std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003661 std::array<uint8_t, 32> calculatedHmac;
3662 std::unique_ptr<VerifiedInputEvent> result;
3663 switch (event.getType()) {
3664 case AINPUT_EVENT_TYPE_KEY: {
3665 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3666 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3667 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003668 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003669 break;
3670 }
3671 case AINPUT_EVENT_TYPE_MOTION: {
3672 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3673 VerifiedMotionEvent verifiedMotionEvent =
3674 verifiedMotionEventFromMotionEvent(motionEvent);
3675 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003676 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003677 break;
3678 }
3679 default: {
3680 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3681 return nullptr;
3682 }
3683 }
3684 if (calculatedHmac == INVALID_HMAC) {
3685 return nullptr;
3686 }
3687 if (calculatedHmac != event.getHmac()) {
3688 return nullptr;
3689 }
3690 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003691}
3692
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003694 return injectorUid == 0 ||
3695 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696}
3697
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003698void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 InjectionState* injectionState = entry->injectionState;
3700 if (injectionState) {
3701#if DEBUG_INJECTION
3702 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003703 "injectorPid=%d, injectorUid=%d",
3704 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705#endif
3706
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 // Log the outcome since the injector did not wait for the injection result.
3709 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003710 case INPUT_EVENT_INJECTION_SUCCEEDED:
3711 ALOGV("Asynchronous input event injection succeeded.");
3712 break;
3713 case INPUT_EVENT_INJECTION_FAILED:
3714 ALOGW("Asynchronous input event injection failed.");
3715 break;
3716 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3717 ALOGW("Asynchronous input event injection permission denied.");
3718 break;
3719 case INPUT_EVENT_INJECTION_TIMED_OUT:
3720 ALOGW("Asynchronous input event injection timed out.");
3721 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 }
3723 }
3724
3725 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003726 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
3728}
3729
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003730void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 InjectionState* injectionState = entry->injectionState;
3732 if (injectionState) {
3733 injectionState->pendingForegroundDispatches += 1;
3734 }
3735}
3736
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003737void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 InjectionState* injectionState = entry->injectionState;
3739 if (injectionState) {
3740 injectionState->pendingForegroundDispatches -= 1;
3741
3742 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003743 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745 }
3746}
3747
Vishnu Nairad321cd2020-08-20 16:40:21 -07003748const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003749 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003750 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3751 auto it = mWindowHandlesByDisplay.find(displayId);
3752 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003753}
3754
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003756 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003757 if (windowHandleToken == nullptr) {
3758 return nullptr;
3759 }
3760
Arthur Hungb92218b2018-08-14 12:00:21 +08003761 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003762 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003763 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003764 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003765 return windowHandle;
3766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
3768 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003769 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770}
3771
Vishnu Nairad321cd2020-08-20 16:40:21 -07003772sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3773 int displayId) const {
3774 if (windowHandleToken == nullptr) {
3775 return nullptr;
3776 }
3777
3778 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3779 if (windowHandle->getToken() == windowHandleToken) {
3780 return windowHandle;
3781 }
3782 }
3783 return nullptr;
3784}
3785
3786sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3787 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3788 return getWindowHandleLocked(focusedToken, displayId);
3789}
3790
Mady Mellor017bcd12020-06-23 19:12:00 +00003791bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3792 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003793 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003794 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003795 if (handle->getId() == windowHandle->getId() &&
3796 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003797 if (windowHandle->getInfo()->displayId != it.first) {
3798 ALOGE("Found window %s in display %" PRId32
3799 ", but it should belong to display %" PRId32,
3800 windowHandle->getName().c_str(), it.first,
3801 windowHandle->getInfo()->displayId);
3802 }
3803 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806 }
3807 return false;
3808}
3809
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003810bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3811 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3812 const bool noInputChannel =
3813 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3814 if (connection != nullptr && noInputChannel) {
3815 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3816 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3817 return false;
3818 }
3819
3820 if (connection == nullptr) {
3821 if (!noInputChannel) {
3822 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3823 }
3824 return false;
3825 }
3826 if (!connection->responsive) {
3827 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3828 return false;
3829 }
3830 return true;
3831}
3832
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003833std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3834 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003835 size_t count = mInputChannelsByToken.count(token);
3836 if (count == 0) {
3837 return nullptr;
3838 }
3839 return mInputChannelsByToken.at(token);
3840}
3841
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003842void InputDispatcher::updateWindowHandlesForDisplayLocked(
3843 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3844 if (inputWindowHandles.empty()) {
3845 // Remove all handles on a display if there are no windows left.
3846 mWindowHandlesByDisplay.erase(displayId);
3847 return;
3848 }
3849
3850 // Since we compare the pointer of input window handles across window updates, we need
3851 // to make sure the handle object for the same window stays unchanged across updates.
3852 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003853 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003854 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003855 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003856 }
3857
3858 std::vector<sp<InputWindowHandle>> newHandles;
3859 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3860 if (!handle->updateInfo()) {
3861 // handle no longer valid
3862 continue;
3863 }
3864
3865 const InputWindowInfo* info = handle->getInfo();
3866 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3867 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3868 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003869 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3870 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3871 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003872 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003873 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003874 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003875 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003876 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003877 }
3878
3879 if (info->displayId != displayId) {
3880 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3881 handle->getName().c_str(), displayId, info->displayId);
3882 continue;
3883 }
3884
Robert Carredd13602020-04-13 17:24:34 -07003885 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3886 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003887 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003888 oldHandle->updateFrom(handle);
3889 newHandles.push_back(oldHandle);
3890 } else {
3891 newHandles.push_back(handle);
3892 }
3893 }
3894
3895 // Insert or replace
3896 mWindowHandlesByDisplay[displayId] = newHandles;
3897}
3898
Arthur Hung72d8dc32020-03-28 00:48:39 +00003899void InputDispatcher::setInputWindows(
3900 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3901 { // acquire lock
3902 std::scoped_lock _l(mLock);
3903 for (auto const& i : handlesPerDisplay) {
3904 setInputWindowsLocked(i.second, i.first);
3905 }
3906 }
3907 // Wake up poll loop since it may need to make new input dispatching choices.
3908 mLooper->wake();
3909}
3910
Arthur Hungb92218b2018-08-14 12:00:21 +08003911/**
3912 * Called from InputManagerService, update window handle list by displayId that can receive input.
3913 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3914 * If set an empty list, remove all handles from the specific display.
3915 * For focused handle, check if need to change and send a cancel event to previous one.
3916 * For removed handle, check if need to send a cancel event if already in touch.
3917 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003918void InputDispatcher::setInputWindowsLocked(
3919 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003920 if (DEBUG_FOCUS) {
3921 std::string windowList;
3922 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3923 windowList += iwh->getName() + " ";
3924 }
3925 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003928 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3929 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3930 const bool noInputWindow =
3931 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3932 if (noInputWindow && window->getToken() != nullptr) {
3933 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3934 window->getName().c_str());
3935 window->releaseChannel();
3936 }
3937 }
3938
Arthur Hung72d8dc32020-03-28 00:48:39 +00003939 // Copy old handles for release if they are no longer present.
3940 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941
Arthur Hung72d8dc32020-03-28 00:48:39 +00003942 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003943
Vishnu Nair958da932020-08-21 17:12:37 -07003944 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3945 if (mLastHoverWindowHandle &&
3946 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3947 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003948 mLastHoverWindowHandle = nullptr;
3949 }
3950
Vishnu Nair958da932020-08-21 17:12:37 -07003951 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3952 if (focusedToken) {
3953 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3954 if (result != FocusResult::OK) {
3955 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3956 }
3957 }
3958
3959 std::optional<FocusRequest> focusRequest =
3960 getOptionalValueByKey(mPendingFocusRequests, displayId);
3961 if (focusRequest) {
3962 // If the window from the pending request is now visible, provide it focus.
3963 FocusResult result = handleFocusRequestLocked(*focusRequest);
3964 if (result != FocusResult::NOT_VISIBLE) {
3965 // Drop the request if we were able to change the focus or we cannot change
3966 // it for another reason.
3967 mPendingFocusRequests.erase(displayId);
3968 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003971 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3972 mTouchStatesByDisplay.find(displayId);
3973 if (stateIt != mTouchStatesByDisplay.end()) {
3974 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003975 for (size_t i = 0; i < state.windows.size();) {
3976 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003977 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003978 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003979 ALOGD("Touched window was removed: %s in display %" PRId32,
3980 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003981 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003982 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003983 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3984 if (touchedInputChannel != nullptr) {
3985 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3986 "touched window was removed");
3987 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003989 state.windows.erase(state.windows.begin() + i);
3990 } else {
3991 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003994 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003995
Arthur Hung72d8dc32020-03-28 00:48:39 +00003996 // Release information for windows that are no longer present.
3997 // This ensures that unused input channels are released promptly.
3998 // Otherwise, they might stick around until the window handle is destroyed
3999 // which might not happen until the next GC.
4000 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004001 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004002 if (DEBUG_FOCUS) {
4003 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004004 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004005 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004006 }
chaviw291d88a2019-02-14 10:33:58 -08004007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008}
4009
4010void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004011 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004012 if (DEBUG_FOCUS) {
4013 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4014 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4015 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004016 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004017 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
Chris Yea209fde2020-07-22 13:54:51 -07004019 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004020 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004021
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004022 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4023 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004024 }
4025
Chris Yea209fde2020-07-22 13:54:51 -07004026 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004027 if (inputApplicationHandle != nullptr) {
4028 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4029 } else {
4030 mFocusedApplicationHandlesByDisplay.erase(displayId);
4031 }
4032
4033 // No matter what the old focused application was, stop waiting on it because it is
4034 // no longer focused.
4035 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 } // release lock
4037
4038 // Wake up poll loop since it may need to make new input dispatching choices.
4039 mLooper->wake();
4040}
4041
Tiger Huang721e26f2018-07-24 22:26:19 +08004042/**
4043 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4044 * the display not specified.
4045 *
4046 * We track any unreleased events for each window. If a window loses the ability to receive the
4047 * released event, we will send a cancel event to it. So when the focused display is changed, we
4048 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4049 * display. The display-specified events won't be affected.
4050 */
4051void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004052 if (DEBUG_FOCUS) {
4053 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4054 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004055 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004056 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004057
4058 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004059 sp<IBinder> oldFocusedWindowToken =
4060 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4061 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004062 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004063 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004064 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 CancelationOptions
4066 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4067 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004068 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004069 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4070 }
4071 }
4072 mFocusedDisplayId = displayId;
4073
Chris Ye3c2d6f52020-08-09 10:39:48 -07004074 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004075 sp<IBinder> newFocusedWindowToken =
4076 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4077 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004078
Vishnu Nairad321cd2020-08-20 16:40:21 -07004079 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004080 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004081 if (!mFocusedWindowTokenByDisplay.empty()) {
4082 ALOGE("But another display has a focused window\n%s",
4083 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004084 }
4085 }
4086 }
4087
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004088 if (DEBUG_FOCUS) {
4089 logDispatchStateLocked();
4090 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004091 } // release lock
4092
4093 // Wake up poll loop since it may need to make new input dispatching choices.
4094 mLooper->wake();
4095}
4096
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004098 if (DEBUG_FOCUS) {
4099 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
4102 bool changed;
4103 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004104 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
4106 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4107 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004108 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
4110
4111 if (mDispatchEnabled && !enabled) {
4112 resetAndDropEverythingLocked("dispatcher is being disabled");
4113 }
4114
4115 mDispatchEnabled = enabled;
4116 mDispatchFrozen = frozen;
4117 changed = true;
4118 } else {
4119 changed = false;
4120 }
4121
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004122 if (DEBUG_FOCUS) {
4123 logDispatchStateLocked();
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 } // release lock
4126
4127 if (changed) {
4128 // Wake up poll loop since it may need to make new input dispatching choices.
4129 mLooper->wake();
4130 }
4131}
4132
4133void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004134 if (DEBUG_FOCUS) {
4135 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137
4138 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004139 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140
4141 if (mInputFilterEnabled == enabled) {
4142 return;
4143 }
4144
4145 mInputFilterEnabled = enabled;
4146 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4147 } // release lock
4148
4149 // Wake up poll loop since there might be work to do to drop everything.
4150 mLooper->wake();
4151}
4152
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004153void InputDispatcher::setInTouchMode(bool inTouchMode) {
4154 std::scoped_lock lock(mLock);
4155 mInTouchMode = inTouchMode;
4156}
4157
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004158void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4159 if (opacity < 0 || opacity > 1) {
4160 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4161 return;
4162 }
4163
4164 std::scoped_lock lock(mLock);
4165 mMaximumObscuringOpacityForTouch = opacity;
4166}
4167
4168void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4169 std::scoped_lock lock(mLock);
4170 mBlockUntrustedTouchesMode = mode;
4171}
4172
chaviwfbe5d9c2018-12-26 12:23:37 -08004173bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4174 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004175 if (DEBUG_FOCUS) {
4176 ALOGD("Trivial transfer to same window.");
4177 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004178 return true;
4179 }
4180
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004182 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
chaviwfbe5d9c2018-12-26 12:23:37 -08004184 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4185 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004186 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004187 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 return false;
4189 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004190 if (DEBUG_FOCUS) {
4191 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4192 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004195 if (DEBUG_FOCUS) {
4196 ALOGD("Cannot transfer focus because windows are on different displays.");
4197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 return false;
4199 }
4200
4201 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004202 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4203 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004204 for (size_t i = 0; i < state.windows.size(); i++) {
4205 const TouchedWindow& touchedWindow = state.windows[i];
4206 if (touchedWindow.windowHandle == fromWindowHandle) {
4207 int32_t oldTargetFlags = touchedWindow.targetFlags;
4208 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004210 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 int32_t newTargetFlags = oldTargetFlags &
4213 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4214 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004215 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Jeff Brownf086ddb2014-02-11 14:28:48 -08004217 found = true;
4218 goto Found;
4219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004225 if (DEBUG_FOCUS) {
4226 ALOGD("Focus transfer failed because from window did not have focus.");
4227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 return false;
4229 }
4230
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004231 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4232 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004233 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004234 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 CancelationOptions
4236 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4237 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004239 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 }
4241
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004242 if (DEBUG_FOCUS) {
4243 logDispatchStateLocked();
4244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 } // release lock
4246
4247 // Wake up poll loop since it may need to make new input dispatching choices.
4248 mLooper->wake();
4249 return true;
4250}
4251
4252void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004253 if (DEBUG_FOCUS) {
4254 ALOGD("Resetting and dropping all events (%s).", reason);
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
4257 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4258 synthesizeCancelationEventsForAllConnectionsLocked(options);
4259
4260 resetKeyRepeatLocked();
4261 releasePendingEventLocked();
4262 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004263 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004265 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004266 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004268 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269}
4270
4271void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 dumpDispatchStateLocked(dump);
4274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 std::istringstream stream(dump);
4276 std::string line;
4277
4278 while (std::getline(stream, line, '\n')) {
4279 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281}
4282
Vishnu Nairad321cd2020-08-20 16:40:21 -07004283std::string InputDispatcher::dumpFocusedWindowsLocked() {
4284 if (mFocusedWindowTokenByDisplay.empty()) {
4285 return INDENT "FocusedWindows: <none>\n";
4286 }
4287
4288 std::string dump;
4289 dump += INDENT "FocusedWindows:\n";
4290 for (auto& it : mFocusedWindowTokenByDisplay) {
4291 const int32_t displayId = it.first;
4292 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4293 if (windowHandle) {
4294 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4295 windowHandle->getName().c_str());
4296 } else {
4297 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4298 " has focused token without a window'\n",
4299 displayId);
4300 }
4301 }
4302 return dump;
4303}
4304
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004305void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004306 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4307 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4308 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004309 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310
Tiger Huang721e26f2018-07-24 22:26:19 +08004311 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4312 dump += StringPrintf(INDENT "FocusedApplications:\n");
4313 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4314 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004315 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004316 const std::chrono::duration timeout =
4317 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004320 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004323 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004325
Vishnu Nairad321cd2020-08-20 16:40:21 -07004326 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004328 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004329 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004330 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4331 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 state.displayId, toString(state.down), toString(state.split),
4334 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004335 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004336 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004337 for (size_t i = 0; i < state.windows.size(); i++) {
4338 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 dump += StringPrintf(INDENT4
4340 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4341 i, touchedWindow.windowHandle->getName().c_str(),
4342 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004343 }
4344 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004345 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004346 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004347 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004348 dump += INDENT3 "Portal windows:\n";
4349 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004350 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4352 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004353 }
4354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 }
4356 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004357 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 }
4359
Arthur Hungb92218b2018-08-14 12:00:21 +08004360 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004362 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004363 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004364 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004365 dump += INDENT2 "Windows:\n";
4366 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004367 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004368 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
Arthur Hungb92218b2018-08-14 12:00:21 +08004370 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004371 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4372 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004373 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004375 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004376 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 i, windowInfo->name.c_str(), windowInfo->displayId,
4378 windowInfo->portalToDisplayId,
4379 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004380 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 toString(windowInfo->hasWallpaper),
4382 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004383 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004384 static_cast<int32_t>(windowInfo->type),
4385 windowInfo->frameLeft, windowInfo->frameTop,
4386 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004387 windowInfo->globalScaleFactor,
4388 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004389 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004390 dump += StringPrintf(", inputFeatures=%s",
4391 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004392 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4393 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004395 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004396 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004397 }
4398 } else {
4399 dump += INDENT2 "Windows: <none>\n";
4400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 }
4402 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004403 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 }
4405
Michael Wright3dd60e22019-03-27 22:06:44 +00004406 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004408 const std::vector<Monitor>& monitors = it.second;
4409 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4410 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 }
4412 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004413 const std::vector<Monitor>& monitors = it.second;
4414 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4415 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004418 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 }
4420
4421 nsecs_t currentTime = now();
4422
4423 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004424 if (!mRecentQueue.empty()) {
4425 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4426 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004427 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004429 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
4431 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004432 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 }
4434
4435 // Dump event currently being dispatched.
4436 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004437 dump += INDENT "PendingEvent:\n";
4438 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004440 dump += StringPrintf(", age=%" PRId64 "ms\n",
4441 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004443 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 }
4445
4446 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004447 if (!mInboundQueue.empty()) {
4448 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4449 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004450 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004452 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004455 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 }
4457
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004458 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004459 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004460 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4461 const KeyReplacement& replacement = pair.first;
4462 int32_t newKeyCode = pair.second;
4463 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004465 }
4466 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004467 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004468 }
4469
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004470 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004471 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004472 for (const auto& pair : mConnectionsByFd) {
4473 const sp<Connection>& connection = pair.second;
4474 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004475 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004476 pair.first, connection->getInputChannelName().c_str(),
4477 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004478 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004480 if (!connection->outboundQueue.empty()) {
4481 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4482 connection->outboundQueue.size());
4483 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 dump.append(INDENT4);
4485 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004486 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4487 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004488 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004489 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 }
4491 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004492 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
4494
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004495 if (!connection->waitQueue.empty()) {
4496 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4497 connection->waitQueue.size());
4498 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004499 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004501 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004502 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004504 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004505 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 }
4507 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004508 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
4510 }
4511 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004512 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 }
4514
4515 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004516 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4517 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004519 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
4521
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004522 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004523 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4524 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4525 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526}
4527
Michael Wright3dd60e22019-03-27 22:06:44 +00004528void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4529 const size_t numMonitors = monitors.size();
4530 for (size_t i = 0; i < numMonitors; i++) {
4531 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004532 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004533 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4534 dump += "\n";
4535 }
4536}
4537
Garfield Tan15601662020-09-22 15:32:38 -07004538base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4539 const std::string& name) {
4540#if DEBUG_CHANNEL_CREATION
4541 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542#endif
4543
Garfield Tan15601662020-09-22 15:32:38 -07004544 std::shared_ptr<InputChannel> serverChannel;
4545 std::unique_ptr<InputChannel> clientChannel;
4546 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4547
4548 if (result) {
4549 return base::Error(result) << "Failed to open input channel pair with name " << name;
4550 }
4551
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004553 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004554 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555
Garfield Tan15601662020-09-22 15:32:38 -07004556 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004557 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004558 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4561 } // release lock
4562
4563 // Wake the looper because some connections have changed.
4564 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004565 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566}
4567
Garfield Tan15601662020-09-22 15:32:38 -07004568base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4569 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4570 std::shared_ptr<InputChannel> serverChannel;
4571 std::unique_ptr<InputChannel> clientChannel;
4572 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4573 if (result) {
4574 return base::Error(result) << "Failed to open input channel pair with name " << name;
4575 }
4576
Michael Wright3dd60e22019-03-27 22:06:44 +00004577 { // acquire lock
4578 std::scoped_lock _l(mLock);
4579
4580 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004581 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4582 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004583 }
4584
Garfield Tan15601662020-09-22 15:32:38 -07004585 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004586
Garfield Tan15601662020-09-22 15:32:38 -07004587 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004588 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004589 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004590
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004591 auto& monitorsByDisplay =
4592 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004593 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004594
4595 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004596 }
Garfield Tan15601662020-09-22 15:32:38 -07004597
Michael Wright3dd60e22019-03-27 22:06:44 +00004598 // Wake the looper because some connections have changed.
4599 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004600 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004601}
4602
Garfield Tan15601662020-09-22 15:32:38 -07004603status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004605 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606
Garfield Tan15601662020-09-22 15:32:38 -07004607 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 if (status) {
4609 return status;
4610 }
4611 } // release lock
4612
4613 // Wake the poll loop because removing the connection may have changed the current
4614 // synchronization state.
4615 mLooper->wake();
4616 return OK;
4617}
4618
Garfield Tan15601662020-09-22 15:32:38 -07004619status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4620 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004621 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004622 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004623 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 return BAD_VALUE;
4625 }
4626
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004627 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004628 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004629
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004631 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 }
4633
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004634 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635
4636 nsecs_t currentTime = now();
4637 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4638
4639 connection->status = Connection::STATUS_ZOMBIE;
4640 return OK;
4641}
4642
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004643void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4644 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4645 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004646}
4647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004649 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004650 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004651 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004652 std::vector<Monitor>& monitors = it->second;
4653 const size_t numMonitors = monitors.size();
4654 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004655 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004656 monitors.erase(monitors.begin() + i);
4657 break;
4658 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004659 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004660 if (monitors.empty()) {
4661 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004662 } else {
4663 ++it;
4664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
4666}
4667
Michael Wright3dd60e22019-03-27 22:06:44 +00004668status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4669 { // acquire lock
4670 std::scoped_lock _l(mLock);
4671 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4672
4673 if (!foundDisplayId) {
4674 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4675 return BAD_VALUE;
4676 }
4677 int32_t displayId = foundDisplayId.value();
4678
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004679 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4680 mTouchStatesByDisplay.find(displayId);
4681 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004682 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4683 return BAD_VALUE;
4684 }
4685
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004686 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004687 std::optional<int32_t> foundDeviceId;
4688 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004689 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004690 foundDeviceId = state.deviceId;
4691 }
4692 }
4693 if (!foundDeviceId || !state.down) {
4694 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004695 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004696 return BAD_VALUE;
4697 }
4698 int32_t deviceId = foundDeviceId.value();
4699
4700 // Send cancel events to all the input channels we're stealing from.
4701 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004702 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004703 options.deviceId = deviceId;
4704 options.displayId = displayId;
4705 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004706 std::shared_ptr<InputChannel> channel =
4707 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004708 if (channel != nullptr) {
4709 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4710 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004711 }
4712 // Then clear the current touch state so we stop dispatching to them as well.
4713 state.filterNonMonitors();
4714 }
4715 return OK;
4716}
4717
Michael Wright3dd60e22019-03-27 22:06:44 +00004718std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4719 const sp<IBinder>& token) {
4720 for (const auto& it : mGestureMonitorsByDisplay) {
4721 const std::vector<Monitor>& monitors = it.second;
4722 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004723 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004724 return it.first;
4725 }
4726 }
4727 }
4728 return std::nullopt;
4729}
4730
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004731sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004732 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004733 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004734 }
4735
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004736 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004737 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004738 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004739 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 }
4741 }
Robert Carr4e670e52018-08-15 13:26:12 -07004742
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004743 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744}
4745
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004746void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004748 removeByValue(mConnectionsByFd, connection);
4749}
4750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4752 const sp<Connection>& connection, uint32_t seq,
4753 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004754 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4755 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 commandEntry->connection = connection;
4757 commandEntry->eventTime = currentTime;
4758 commandEntry->seq = seq;
4759 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004760 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761}
4762
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4764 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004766 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004768 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4769 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004771 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772}
4773
Vishnu Nairad321cd2020-08-20 16:40:21 -07004774void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4775 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004776 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4777 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004778 commandEntry->oldToken = oldToken;
4779 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004780 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004781}
4782
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004783void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4785 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004786 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004787 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004788 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 return;
4790 }
4791 /**
4792 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4793 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4794 * has changed. This could cause newer entries to time out before the already dispatched
4795 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4796 * processes the events linearly. So providing information about the oldest entry seems to be
4797 * most useful.
4798 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004799 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4801 std::string reason =
4802 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004803 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804 ns2ms(currentWait),
4805 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004807 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 reason);
4809
4810 std::unique_ptr<CommandEntry> commandEntry =
4811 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4812 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004813 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 commandEntry->reason = std::move(reason);
4815 postCommandLocked(std::move(commandEntry));
4816}
4817
Chris Yea209fde2020-07-22 13:54:51 -07004818void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004819 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4820 application->getName().c_str());
4821
4822 updateLastAnrStateLocked(application, reason);
4823
4824 std::unique_ptr<CommandEntry> commandEntry =
4825 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4826 commandEntry->inputApplicationHandle = application;
4827 commandEntry->inputChannel = nullptr;
4828 commandEntry->reason = std::move(reason);
4829 postCommandLocked(std::move(commandEntry));
4830}
4831
4832void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4833 const std::string& reason) {
4834 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4835 updateLastAnrStateLocked(windowLabel, reason);
4836}
4837
Chris Yea209fde2020-07-22 13:54:51 -07004838void InputDispatcher::updateLastAnrStateLocked(
4839 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4841 updateLastAnrStateLocked(windowLabel, reason);
4842}
4843
4844void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4845 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004847 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 struct tm tm;
4849 localtime_r(&t, &tm);
4850 char timestr[64];
4851 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004852 mLastAnrState.clear();
4853 mLastAnrState += INDENT "ANR:\n";
4854 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4856 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004857 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858}
4859
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 mLock.unlock();
4862
4863 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4864
4865 mLock.lock();
4866}
4867
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004868void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 sp<Connection> connection = commandEntry->connection;
4870
4871 if (connection->status != Connection::STATUS_ZOMBIE) {
4872 mLock.unlock();
4873
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004874 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
4876 mLock.lock();
4877 }
4878}
4879
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004880void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004881 sp<IBinder> oldToken = commandEntry->oldToken;
4882 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004883 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004884 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004885 mLock.lock();
4886}
4887
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004888void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004889 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004890 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 mLock.unlock();
4892
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004893 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004894 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895
4896 mLock.lock();
4897
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004898 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4900 } else {
4901 // stop waking up for events in this connection, it is already not responding
4902 sp<Connection> connection = getConnectionLocked(token);
4903 if (connection == nullptr) {
4904 return;
4905 }
4906 cancelEventsForAnrLocked(connection);
4907 }
4908}
4909
Chris Yea209fde2020-07-22 13:54:51 -07004910void InputDispatcher::extendAnrTimeoutsLocked(
4911 const std::shared_ptr<InputApplicationHandle>& application,
4912 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004913 if (connectionToken == nullptr && application != nullptr) {
4914 // The ANR happened because there's no focused window
4915 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4916 mAwaitedFocusedApplication = application;
4917 }
4918
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 sp<Connection> connection = getConnectionLocked(connectionToken);
4920 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004921 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 return;
4923 }
4924
4925 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004926 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004927
4928 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004929 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930 for (DispatchEntry* entry : connection->waitQueue) {
4931 if (newTimeout >= entry->timeoutTime) {
4932 // Already removed old entries when connection was marked unresponsive
4933 entry->timeoutTime = newTimeout;
4934 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4935 }
4936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937}
4938
4939void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4940 CommandEntry* commandEntry) {
4941 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004942 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
4944 mLock.unlock();
4945
Michael Wright2b3c3302018-03-02 17:19:13 +00004946 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004947 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004948 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004949 : nullptr;
4950 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004951 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4952 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004953 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
4956 mLock.lock();
4957
4958 if (delay < 0) {
4959 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4960 } else if (!delay) {
4961 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4962 } else {
4963 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4964 entry->interceptKeyWakeupTime = now() + delay;
4965 }
4966 entry->release();
4967}
4968
chaviwfd6d3512019-03-25 13:23:49 -07004969void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4970 mLock.unlock();
4971 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4972 mLock.lock();
4973}
4974
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975/**
4976 * Connection is responsive if it has no events in the waitQueue that are older than the
4977 * current time.
4978 */
4979static bool isConnectionResponsive(const Connection& connection) {
4980 const nsecs_t currentTime = now();
4981 for (const DispatchEntry* entry : connection.waitQueue) {
4982 if (entry->timeoutTime < currentTime) {
4983 return false;
4984 }
4985 }
4986 return true;
4987}
4988
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004991 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004993 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994
4995 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004996 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004997 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004998 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005000 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005001 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005002 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005003 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5004 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005005 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005006 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005007
5008 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005009 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005010 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5011 restartEvent =
5012 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005013 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005014 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5015 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5016 handled);
5017 } else {
5018 restartEvent = false;
5019 }
5020
5021 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005022 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005023 // contents of the wait queue to have been drained, so we need to double-check
5024 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005025 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5026 if (dispatchEntryIt != connection->waitQueue.end()) {
5027 dispatchEntry = *dispatchEntryIt;
5028 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005029 mAnrTracker.erase(dispatchEntry->timeoutTime,
5030 connection->inputChannel->getConnectionToken());
5031 if (!connection->responsive) {
5032 connection->responsive = isConnectionResponsive(*connection);
5033 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005034 traceWaitQueueLength(connection);
5035 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005036 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005037 traceOutboundQueueLength(connection);
5038 } else {
5039 releaseDispatchEntry(dispatchEntry);
5040 }
5041 }
5042
5043 // Start the next dispatch cycle for this connection.
5044 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045}
5046
5047bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005048 DispatchEntry* dispatchEntry,
5049 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005050 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005051 if (!handled) {
5052 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005053 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005054 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005055 return false;
5056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005058 // Get the fallback key state.
5059 // Clear it out after dispatching the UP.
5060 int32_t originalKeyCode = keyEntry->keyCode;
5061 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5062 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5063 connection->inputState.removeFallbackKey(originalKeyCode);
5064 }
5065
5066 if (handled || !dispatchEntry->hasForegroundTarget()) {
5067 // If the application handles the original key for which we previously
5068 // generated a fallback or if the window is not a foreground window,
5069 // then cancel the associated fallback key, if any.
5070 if (fallbackKeyCode != -1) {
5071 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005073 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005074 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5075 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5076 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005078 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005079 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080
5081 mLock.unlock();
5082
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005083 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005084 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085
5086 mLock.lock();
5087
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005088 // Cancel the fallback key.
5089 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005091 "application handled the original non-fallback key "
5092 "or is no longer a foreground target, "
5093 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 options.keyCode = fallbackKeyCode;
5095 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005097 connection->inputState.removeFallbackKey(originalKeyCode);
5098 }
5099 } else {
5100 // If the application did not handle a non-fallback key, first check
5101 // that we are in a good state to perform unhandled key event processing
5102 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005103 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005104 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005106 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 "since this is not an initial down. "
5108 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5109 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005111 return false;
5112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005114 // Dispatch the unhandled key to the policy.
5115#if DEBUG_OUTBOUND_EVENT_DETAILS
5116 ALOGD("Unhandled key event: Asking policy to perform 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, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005119#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005120 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005121
5122 mLock.unlock();
5123
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005124 bool fallback =
5125 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5126 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005127
5128 mLock.lock();
5129
5130 if (connection->status != Connection::STATUS_NORMAL) {
5131 connection->inputState.removeFallbackKey(originalKeyCode);
5132 return false;
5133 }
5134
5135 // Latch the fallback keycode for this key on an initial down.
5136 // The fallback keycode cannot change at any other point in the lifecycle.
5137 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005139 fallbackKeyCode = event.getKeyCode();
5140 } else {
5141 fallbackKeyCode = AKEYCODE_UNKNOWN;
5142 }
5143 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5144 }
5145
5146 ALOG_ASSERT(fallbackKeyCode != -1);
5147
5148 // Cancel the fallback key if the policy decides not to send it anymore.
5149 // We will continue to dispatch the key to the policy but we will no
5150 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5152 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005153#if DEBUG_OUTBOUND_EVENT_DETAILS
5154 if (fallback) {
5155 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 "as a fallback for %d, but on the DOWN it had requested "
5157 "to send %d instead. Fallback canceled.",
5158 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005159 } else {
5160 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005161 "but on the DOWN it had requested to send %d. "
5162 "Fallback canceled.",
5163 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005164 }
5165#endif
5166
5167 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5168 "canceling fallback, policy no longer desires it");
5169 options.keyCode = fallbackKeyCode;
5170 synthesizeCancelationEventsForConnectionLocked(connection, options);
5171
5172 fallback = false;
5173 fallbackKeyCode = AKEYCODE_UNKNOWN;
5174 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005176 }
5177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178
5179#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005180 {
5181 std::string msg;
5182 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5183 connection->inputState.getFallbackKeys();
5184 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005185 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005187 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005188 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005189 }
5190#endif
5191
5192 if (fallback) {
5193 // Restart the dispatch cycle using the fallback key.
5194 keyEntry->eventTime = event.getEventTime();
5195 keyEntry->deviceId = event.getDeviceId();
5196 keyEntry->source = event.getSource();
5197 keyEntry->displayId = event.getDisplayId();
5198 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5199 keyEntry->keyCode = fallbackKeyCode;
5200 keyEntry->scanCode = event.getScanCode();
5201 keyEntry->metaState = event.getMetaState();
5202 keyEntry->repeatCount = event.getRepeatCount();
5203 keyEntry->downTime = event.getDownTime();
5204 keyEntry->syntheticRepeat = false;
5205
5206#if DEBUG_OUTBOUND_EVENT_DETAILS
5207 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5209 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005210#endif
5211 return true; // restart the event
5212 } else {
5213#if DEBUG_OUTBOUND_EVENT_DETAILS
5214 ALOGD("Unhandled key event: No fallback key.");
5215#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005216
5217 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005218 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
5220 }
5221 return false;
5222}
5223
5224bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005225 DispatchEntry* dispatchEntry,
5226 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 return false;
5228}
5229
5230void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5231 mLock.unlock();
5232
5233 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5234
5235 mLock.lock();
5236}
5237
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005238KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5239 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005240 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005241 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5242 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005243 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244}
5245
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005246void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5247 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 // TODO Write some statistics about how long we spend waiting.
5249}
5250
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005251/**
5252 * Report the touch event latency to the statsd server.
5253 * Input events are reported for statistics if:
5254 * - This is a touchscreen event
5255 * - InputFilter is not enabled
5256 * - Event is not injected or synthesized
5257 *
5258 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5259 * from getting aggregated with the "old" data.
5260 */
5261void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5262 REQUIRES(mLock) {
5263 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5264 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5265 if (!reportForStatistics) {
5266 return;
5267 }
5268
5269 if (mTouchStatistics.shouldReport()) {
5270 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5271 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5272 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5273 mTouchStatistics.reset();
5274 }
5275 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5276 mTouchStatistics.addValue(latencyMicros);
5277}
5278
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279void InputDispatcher::traceInboundQueueLengthLocked() {
5280 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005281 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
5283}
5284
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005285void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 if (ATRACE_ENABLED()) {
5287 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005288 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005289 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291}
5292
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005293void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 if (ATRACE_ENABLED()) {
5295 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005296 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005297 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
5299}
5300
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005301void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005302 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005304 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 dumpDispatchStateLocked(dump);
5306
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005307 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005309 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311}
5312
5313void InputDispatcher::monitor() {
5314 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005315 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005317 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318}
5319
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005320/**
5321 * Wake up the dispatcher and wait until it processes all events and commands.
5322 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5323 * this method can be safely called from any thread, as long as you've ensured that
5324 * the work you are interested in completing has already been queued.
5325 */
5326bool InputDispatcher::waitForIdle() {
5327 /**
5328 * Timeout should represent the longest possible time that a device might spend processing
5329 * events and commands.
5330 */
5331 constexpr std::chrono::duration TIMEOUT = 100ms;
5332 std::unique_lock lock(mLock);
5333 mLooper->wake();
5334 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5335 return result == std::cv_status::no_timeout;
5336}
5337
Vishnu Naire798b472020-07-23 13:52:21 -07005338/**
5339 * Sets focus to the window identified by the token. This must be called
5340 * after updating any input window handles.
5341 *
5342 * Params:
5343 * request.token - input channel token used to identify the window that should gain focus.
5344 * request.focusedToken - the token that the caller expects currently to be focused. If the
5345 * specified token does not match the currently focused window, this request will be dropped.
5346 * If the specified focused token matches the currently focused window, the call will succeed.
5347 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5348 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5349 * when requesting the focus change. This determines which request gets
5350 * precedence if there is a focus change request from another source such as pointer down.
5351 */
Vishnu Nair958da932020-08-21 17:12:37 -07005352void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5353 { // acquire lock
5354 std::scoped_lock _l(mLock);
5355
5356 const int32_t displayId = request.displayId;
5357 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5358 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5359 ALOGD_IF(DEBUG_FOCUS,
5360 "setFocusedWindow on display %" PRId32
5361 " ignored, reason: focusedToken is not focused",
5362 displayId);
5363 return;
5364 }
5365
5366 mPendingFocusRequests.erase(displayId);
5367 FocusResult result = handleFocusRequestLocked(request);
5368 if (result == FocusResult::NOT_VISIBLE) {
5369 // The requested window is not currently visible. Wait for the window to become visible
5370 // and then provide it focus. This is to handle situations where a user action triggers
5371 // a new window to appear. We want to be able to queue any key events after the user
5372 // action and deliver it to the newly focused window. In order for this to happen, we
5373 // take focus from the currently focused window so key events can be queued.
5374 ALOGD_IF(DEBUG_FOCUS,
5375 "setFocusedWindow on display %" PRId32
5376 " pending, reason: window is not visible",
5377 displayId);
5378 mPendingFocusRequests[displayId] = request;
5379 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5380 "setFocusedWindow_AwaitingWindowVisibility");
5381 } else if (result != FocusResult::OK) {
5382 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5383 typeToString(result));
5384 }
5385 } // release lock
5386 // Wake up poll loop since it may need to make new input dispatching choices.
5387 mLooper->wake();
5388}
5389
5390InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5391 const FocusRequest& request) {
5392 const int32_t displayId = request.displayId;
5393 const sp<IBinder> newFocusedToken = request.token;
5394 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5395
5396 if (oldFocusedToken == request.token) {
5397 ALOGD_IF(DEBUG_FOCUS,
5398 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5399 displayId);
5400 return FocusResult::OK;
5401 }
5402
5403 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5404 if (result != FocusResult::OK) {
5405 return result;
5406 }
5407
5408 std::string_view reason =
5409 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5410 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5411 return FocusResult::OK;
5412}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005413
Vishnu Nairad321cd2020-08-20 16:40:21 -07005414void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5415 const sp<IBinder>& newFocusedToken, int32_t displayId,
5416 std::string_view reason) {
5417 if (oldFocusedToken) {
5418 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005419 if (focusedInputChannel) {
5420 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5421 "focus left window");
5422 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005423 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005424 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005425 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005426 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005427 if (newFocusedToken) {
5428 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5429 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005430 }
5431
5432 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005433 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005434 }
5435}
Vishnu Nair958da932020-08-21 17:12:37 -07005436
5437/**
5438 * Checks if the window token can be focused on a display. The token can be focused if there is
5439 * at least one window handle that is visible with the same token and all window handles with the
5440 * same token are focusable.
5441 *
5442 * In the case of mirroring, two windows may share the same window token and their visibility
5443 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5444 * we expect the focusability of the windows to match since its hard to reason why one window can
5445 * receive focus events and the other cannot when both are backed by the same input channel.
5446 */
5447InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5448 int32_t displayId) const {
5449 bool allWindowsAreFocusable = true;
5450 bool visibleWindowFound = false;
5451 bool windowFound = false;
5452 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5453 if (window->getToken() != token) {
5454 continue;
5455 }
5456 windowFound = true;
5457 if (window->getInfo()->visible) {
5458 // Check if at least a single window is visible.
5459 visibleWindowFound = true;
5460 }
5461 if (!window->getInfo()->focusable) {
5462 // Check if all windows with the window token are focusable.
5463 allWindowsAreFocusable = false;
5464 break;
5465 }
5466 }
5467
5468 if (!windowFound) {
5469 return FocusResult::NO_WINDOW;
5470 }
5471 if (!allWindowsAreFocusable) {
5472 return FocusResult::NOT_FOCUSABLE;
5473 }
5474 if (!visibleWindowFound) {
5475 return FocusResult::NOT_VISIBLE;
5476 }
5477
5478 return FocusResult::OK;
5479}
Garfield Tane84e6f92019-08-29 17:28:41 -07005480} // namespace android::inputdispatcher