blob: 8b4ae036fabe7c3c8f05d955d87e40c5e28645d9 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
Vishnu Nair958da932020-08-21 17:12:37 -0700255/**
256 * Find the entry in std::unordered_map by key and return the value as an optional.
257 */
258template <typename K, typename V>
259static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
260 auto it = map.find(key);
261 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
262}
263
chaviwaf87b3e2019-10-01 16:59:28 -0700264static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
265 if (first == second) {
266 return true;
267 }
268
269 if (first == nullptr || second == nullptr) {
270 return false;
271 }
272
273 return first->getToken() == second->getToken();
274}
275
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800276static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
277 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
278}
279
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000280static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
281 EventEntry* eventEntry,
282 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700283 if (inputTarget.useDefaultPointerTransform()) {
284 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000285 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700286 inputTargetFlags, transform,
287 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000288 }
289
290 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
291 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
292
293 PointerCoords pointerCoords[motionEntry.pointerCount];
294
295 // Use the first pointer information to normalize all other pointers. This could be any pointer
296 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 // uses the transform for the normalized pointer.
298 const ui::Transform& firstPointerTransform =
299 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
300 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000301
302 // Iterate through all pointers in the event to normalize against the first.
303 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
304 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
305 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700306 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 // First, apply the current pointer's transform to update the coordinates into
310 // window space.
311 pointerCoords[pointerIndex].transform(currTransform);
312 // Next, apply the inverse transform of the normalized coordinates so the
313 // current coordinates are transformed into the normalized coordinate space.
314 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 }
316
317 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800318 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
320 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
321 motionEntry.metaState, motionEntry.buttonState,
322 motionEntry.classification, motionEntry.edgeFlags,
323 motionEntry.xPrecision, motionEntry.yPrecision,
324 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
325 motionEntry.downTime, motionEntry.pointerCount,
326 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
327 0 /* yOffset */);
328
329 if (motionEntry.injectionState) {
330 combinedMotionEntry->injectionState = motionEntry.injectionState;
331 combinedMotionEntry->injectionState->refCount += 1;
332 }
333
334 std::unique_ptr<DispatchEntry> dispatchEntry =
335 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 inputTargetFlags, firstPointerTransform,
337 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 combinedMotionEntry->release();
339 return dispatchEntry;
340}
341
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700342static void addGestureMonitors(const std::vector<Monitor>& monitors,
343 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
344 float yOffset = 0) {
345 if (monitors.empty()) {
346 return;
347 }
348 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
349 for (const Monitor& monitor : monitors) {
350 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
351 }
352}
353
Garfield Tan15601662020-09-22 15:32:38 -0700354static status_t openInputChannelPair(const std::string& name,
355 std::shared_ptr<InputChannel>& serverChannel,
356 std::unique_ptr<InputChannel>& clientChannel) {
357 std::unique_ptr<InputChannel> uniqueServerChannel;
358 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
359
360 serverChannel = std::move(uniqueServerChannel);
361 return result;
362}
363
Vishnu Nair958da932020-08-21 17:12:37 -0700364const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
365 switch (result) {
366 case InputDispatcher::FocusResult::OK:
367 return "Ok";
368 case InputDispatcher::FocusResult::NO_WINDOW:
369 return "Window not found";
370 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
371 return "Window not focusable";
372 case InputDispatcher::FocusResult::NOT_VISIBLE:
373 return "Window not visible";
374 }
375}
376
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500377template <typename T>
378static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
379 if (lhs == nullptr && rhs == nullptr) {
380 return true;
381 }
382 if (lhs == nullptr || rhs == nullptr) {
383 return false;
384 }
385 return *lhs == *rhs;
386}
387
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388// --- InputDispatcher ---
389
Garfield Tan00f511d2019-06-12 16:55:40 -0700390InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
391 : mPolicy(policy),
392 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700393 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800394 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700395 mAppSwitchSawKeyDown(false),
396 mAppSwitchDueTime(LONG_LONG_MAX),
397 mNextUnblockedEvent(nullptr),
398 mDispatchEnabled(false),
399 mDispatchFrozen(false),
400 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800401 // mInTouchMode will be initialized by the WindowManager to the default device config.
402 // To avoid leaking stack in case that call never comes, and for tests,
403 // initialize it here anyways.
404 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100405 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800408 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
Yi Kong9b14ac62018-07-17 13:48:38 -0700410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 policy->getDispatcherConfiguration(&mConfig);
413}
414
415InputDispatcher::~InputDispatcher() {
416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700426 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 }
428}
429
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700431 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return ALREADY_EXISTS;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437}
438
439status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return INVALID_OPERATION;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread.reset();
445 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446}
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482}
483
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700484/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500485 * Raise ANR if there is no focused window.
486 * Before the ANR is raised, do a final state check:
487 * 1. The currently focused application must be the same one we are waiting for.
488 * 2. Ensure we still don't have a focused window.
489 */
490void InputDispatcher::processNoFocusedWindowAnrLocked() {
491 // Check if the application that we are waiting for is still focused.
492 std::shared_ptr<InputApplicationHandle> focusedApplication =
493 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
494 if (focusedApplication == nullptr ||
495 focusedApplication->getApplicationToken() !=
496 mAwaitedFocusedApplication->getApplicationToken()) {
497 // Unexpected because we should have reset the ANR timer when focused application changed
498 ALOGE("Waited for a focused window, but focused application has already changed to %s",
499 focusedApplication->getName().c_str());
500 return; // The focused application has changed.
501 }
502
503 const sp<InputWindowHandle>& focusedWindowHandle =
504 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
505 if (focusedWindowHandle != nullptr) {
506 return; // We now have a focused window. No need for ANR.
507 }
508 onAnrLocked(mAwaitedFocusedApplication);
509}
510
511/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700512 * Check if any of the connections' wait queues have events that are too old.
513 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
514 * Return the time at which we should wake up next.
515 */
516nsecs_t InputDispatcher::processAnrsLocked() {
517 const nsecs_t currentTime = now();
518 nsecs_t nextAnrCheck = LONG_LONG_MAX;
519 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
520 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
521 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500522 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700523 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500524 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700525 return LONG_LONG_MIN;
526 } else {
527 // Keep waiting
528 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
529 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
530 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
531 }
532 }
533
534 // Check if any connection ANRs are due
535 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
536 if (currentTime < nextAnrCheck) { // most likely scenario
537 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
538 }
539
540 // If we reached here, we have an unresponsive connection.
541 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
542 if (connection == nullptr) {
543 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
544 return nextAnrCheck;
545 }
546 connection->responsive = false;
547 // Stop waking up for this unresponsive connection
548 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500549 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700550 return LONG_LONG_MIN;
551}
552
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500553std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700554 sp<InputWindowHandle> window = getWindowHandleLocked(token);
555 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500556 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700557 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500558 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700559}
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
562 nsecs_t currentTime = now();
563
Jeff Browndc5992e2014-04-11 01:27:26 -0700564 // Reset the key repeat timer whenever normal dispatch is suspended while the
565 // device is in a non-interactive state. This is to ensure that we abort a key
566 // repeat if the device is just coming out of sleep.
567 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 resetKeyRepeatLocked();
569 }
570
571 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
572 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100573 if (DEBUG_FOCUS) {
574 ALOGD("Dispatch frozen. Waiting some more.");
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 return;
577 }
578
579 // Optimize latency of app switches.
580 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
581 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
582 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
583 if (mAppSwitchDueTime < *nextWakeupTime) {
584 *nextWakeupTime = mAppSwitchDueTime;
585 }
586
587 // Ready to start a new event.
588 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700590 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 if (isAppSwitchDue) {
592 // The inbound queue is empty so the app switch key we were waiting
593 // for will never arrive. Stop waiting for it.
594 resetPendingAppSwitchLocked(false);
595 isAppSwitchDue = false;
596 }
597
598 // Synthesize a key repeat if appropriate.
599 if (mKeyRepeatState.lastKeyEntry) {
600 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
601 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
602 } else {
603 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
604 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
605 }
606 }
607 }
608
609 // Nothing to do if there is no pending event.
610 if (!mPendingEvent) {
611 return;
612 }
613 } else {
614 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700615 mPendingEvent = mInboundQueue.front();
616 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 traceInboundQueueLengthLocked();
618 }
619
620 // Poke user activity for this event.
621 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700622 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625
626 // Now we have an event to dispatch.
627 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700628 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700632 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700634 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
636
637 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700638 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
640
641 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700642 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 ConfigurationChangedEntry* typedEntry =
644 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
645 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700646 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700647 break;
648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700650 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700651 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
652 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 break;
655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100657 case EventEntry::Type::FOCUS: {
658 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
659 dispatchFocusLocked(currentTime, typedEntry);
660 done = true;
661 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
662 break;
663 }
664
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700665 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
667 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700668 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 resetPendingAppSwitchLocked(true);
670 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700671 } else if (dropReason == DropReason::NOT_DROPPED) {
672 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 }
674 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700676 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
679 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 }
681 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
682 break;
683 }
684
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700685 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700686 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700687 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
688 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700690 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700691 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700693 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
694 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 }
696 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
700
701 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700702 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Michael Wright3a981722015-06-10 15:26:13 +0100705 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706
707 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 }
710}
711
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700712/**
713 * Return true if the events preceding this incoming motion event should be dropped
714 * Return false otherwise (the default behaviour)
715 */
716bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700718 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719
720 // Optimize case where the current application is unresponsive and the user
721 // decides to touch a window in a different application.
722 // If the application takes too long to catch up then we drop all events preceding
723 // the touch into the other window.
724 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700725 int32_t displayId = motionEntry.displayId;
726 int32_t x = static_cast<int32_t>(
727 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
728 int32_t y = static_cast<int32_t>(
729 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
730 sp<InputWindowHandle> touchedWindowHandle =
731 findTouchedWindowAtLocked(displayId, x, y, nullptr);
732 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700733 touchedWindowHandle->getApplicationToken() !=
734 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700735 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 ALOGI("Pruning input queue because user touched a different application while waiting "
737 "for %s",
738 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700739 return true;
740 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700741
742 // Alternatively, maybe there's a gesture monitor that could handle this event
743 std::vector<TouchedMonitor> gestureMonitors =
744 findTouchedGestureMonitorsLocked(displayId, {});
745 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
746 sp<Connection> connection =
747 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000748 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700749 // This monitor could take more input. Drop all events preceding this
750 // event, so that gesture monitor could get a chance to receive the stream
751 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
752 "responsive gesture monitor that may handle the event",
753 mAwaitedFocusedApplication->getName().c_str());
754 return true;
755 }
756 }
757 }
758
759 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
760 // yet been processed by some connections, the dispatcher will wait for these motion
761 // events to be processed before dispatching the key event. This is because these motion events
762 // may cause a new window to be launched, which the user might expect to receive focus.
763 // To prevent waiting forever for such events, just send the key to the currently focused window
764 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
765 ALOGD("Received a new pointer down event, stop waiting for events to process and "
766 "just send the pending key event to the focused window.");
767 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700768 }
769 return false;
770}
771
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700773 bool needWake = mInboundQueue.empty();
774 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 traceInboundQueueLengthLocked();
776
777 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700778 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 // Optimize app switch latency.
780 // If the application takes too long to catch up then we drop all events preceding
781 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700782 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700791 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 mAppSwitchSawKeyDown = false;
793 needWake = true;
794 }
795 }
796 }
797 break;
798 }
799
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700800 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700801 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
802 mNextUnblockedEvent = entry;
803 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100807 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700808 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
809 break;
810 }
811 case EventEntry::Type::CONFIGURATION_CHANGED:
812 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 // nothing to do
814 break;
815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 return needWake;
819}
820
821void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
822 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700823 mRecentQueue.push_back(entry);
824 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
825 mRecentQueue.front()->release();
826 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828}
829
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700831 int32_t y, TouchState* touchState,
832 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
835 LOG_ALWAYS_FATAL(
836 "Must provide a valid touch state if adding portal windows or outside targets");
837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700839 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800840 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 const InputWindowInfo* windowInfo = windowHandle->getInfo();
842 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100843 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844
845 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100846 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
847 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
848 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800850 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 if (portalToDisplayId != ADISPLAY_ID_NONE &&
852 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800853 if (addPortalWindows) {
854 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700855 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800856 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700857 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 // Found window.
861 return windowHandle;
862 }
863 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800864
Michael Wright44753b12020-07-08 13:48:11 +0100865 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700866 touchState->addOrUpdateWindow(windowHandle,
867 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
868 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 }
872 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700873 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874}
875
Garfield Tane84e6f92019-08-29 17:28:41 -0700876std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700877 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000878 std::vector<TouchedMonitor> touchedMonitors;
879
880 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
881 addGestureMonitors(monitors, touchedMonitors);
882 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
883 const InputWindowInfo* windowInfo = portalWindow->getInfo();
884 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
886 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000887 }
888 return touchedMonitors;
889}
890
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 const char* reason;
893 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 reason = "inbound event was dropped because the policy consumed it";
899 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 case DropReason::DISABLED:
901 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 ALOGI("Dropped event because input dispatch is disabled.");
903 }
904 reason = "inbound event was dropped because input dispatch is disabled";
905 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700906 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 ALOGI("Dropped event because of pending overdue app switch.");
908 reason = "inbound event was dropped because of pending overdue app switch";
909 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700910 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 ALOGI("Dropped event because the current application is not responding and the user "
912 "has started interacting with a different application.");
913 reason = "inbound event was dropped because the current application is not responding "
914 "and the user has started interacting with a different application";
915 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700916 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917 ALOGI("Dropped event because it is stale.");
918 reason = "inbound event was dropped because it is stale";
919 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700920 case DropReason::NOT_DROPPED: {
921 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700926 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700927 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
929 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700932 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700933 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
934 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
936 synthesizeCancelationEventsForAllConnectionsLocked(options);
937 } else {
938 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
939 synthesizeCancelationEventsForAllConnectionsLocked(options);
940 }
941 break;
942 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100943 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700944 case EventEntry::Type::CONFIGURATION_CHANGED:
945 case EventEntry::Type::DEVICE_RESET: {
946 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
947 break;
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
950}
951
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800952static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
954 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955}
956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
958 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
959 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
960 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961}
962
963bool InputDispatcher::isAppSwitchPendingLocked() {
964 return mAppSwitchDueTime != LONG_LONG_MAX;
965}
966
967void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
968 mAppSwitchDueTime = LONG_LONG_MAX;
969
970#if DEBUG_APP_SWITCH
971 if (handled) {
972 ALOGD("App switch has arrived.");
973 } else {
974 ALOGD("App switch was abandoned.");
975 }
976#endif
977}
978
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700980 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981}
982
983bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700984 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 return false;
986 }
987
988 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700989 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700990 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700992 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993
994 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700995 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 return true;
997}
998
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700999void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1000 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001}
1002
1003void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001004 while (!mInboundQueue.empty()) {
1005 EventEntry* entry = mInboundQueue.front();
1006 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 releaseInboundEventLocked(entry);
1008 }
1009 traceInboundQueueLengthLocked();
1010}
1011
1012void InputDispatcher::releasePendingEventLocked() {
1013 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017}
1018
1019void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1020 InjectionState* injectionState = entry->injectionState;
1021 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1022#if DEBUG_DISPATCH_CYCLE
1023 ALOGD("Injected inbound event was dropped.");
1024#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001025 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001028 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030 addRecentEventLocked(entry);
1031 entry->release();
1032}
1033
1034void InputDispatcher::resetKeyRepeatLocked() {
1035 if (mKeyRepeatState.lastKeyEntry) {
1036 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001037 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039}
1040
Garfield Tane84e6f92019-08-29 17:28:41 -07001041KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1043
1044 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001045 uint32_t policyFlags = entry->policyFlags &
1046 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 if (entry->refCount == 1) {
1048 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001049 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 entry->eventTime = currentTime;
1051 entry->policyFlags = policyFlags;
1052 entry->repeatCount += 1;
1053 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001055 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001056 entry->displayId, policyFlags, entry->action, entry->flags,
1057 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059
1060 mKeyRepeatState.lastKeyEntry = newEntry;
1061 entry->release();
1062
1063 entry = newEntry;
1064 }
1065 entry->syntheticRepeat = true;
1066
1067 // Increment reference count since we keep a reference to the event in
1068 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1069 entry->refCount += 1;
1070
1071 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1072 return entry;
1073}
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1076 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001078 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079#endif
1080
1081 // Reset key repeating in case a keyboard device was added or removed or something.
1082 resetKeyRepeatLocked();
1083
1084 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001085 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1086 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 return true;
1090}
1091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001094 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096#endif
1097
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 options.deviceId = entry->deviceId;
1100 synthesizeCancelationEventsForAllConnectionsLocked(options);
1101 return true;
1102}
1103
Vishnu Nairad321cd2020-08-20 16:40:21 -07001104void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001105 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001106 if (mPendingEvent != nullptr) {
1107 // Move the pending event to the front of the queue. This will give the chance
1108 // for the pending event to get dispatched to the newly focused window
1109 mInboundQueue.push_front(mPendingEvent);
1110 mPendingEvent = nullptr;
1111 }
1112
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001113 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001114 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001115
1116 // This event should go to the front of the queue, but behind all other focus events
1117 // Find the last focus event, and insert right after it
1118 std::deque<EventEntry*>::reverse_iterator it =
1119 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1120 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1121
1122 // Maintain the order of focus events. Insert the entry after all other focus events.
1123 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001124}
1125
1126void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001127 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001128 if (channel == nullptr) {
1129 return; // Window has gone away
1130 }
1131 InputTarget target;
1132 target.inputChannel = channel;
1133 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1134 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001135 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1136 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001137 std::string reason = std::string("reason=").append(entry->reason);
1138 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001139 dispatchEventLocked(currentTime, entry, {target});
1140}
1141
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 if (!entry->dispatchInProgress) {
1146 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1147 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1148 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1149 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001150 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 // We have seen two identical key downs in a row which indicates that the device
1152 // driver is automatically generating key repeats itself. We take note of the
1153 // repeat here, but we disable our own next key repeat timer since it is clear that
1154 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001155 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1156 // Make sure we don't get key down from a different device. If a different
1157 // device Id has same key pressed down, the new device Id will replace the
1158 // current one to hold the key repeat with repeat count reset.
1159 // In the future when got a KEY_UP on the device id, drop it and do not
1160 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1162 resetKeyRepeatLocked();
1163 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1164 } else {
1165 // Not a repeat. Save key down state in case we do see a repeat later.
1166 resetKeyRepeatLocked();
1167 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1168 }
1169 mKeyRepeatState.lastKeyEntry = entry;
1170 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001171 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1172 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1173 // The stale device releases the key, reset staleDeviceId.
1174#if DEBUG_INBOUND_EVENT_DETAILS
1175 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1176#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 resetKeyRepeatLocked();
1179 }
1180
1181 if (entry->repeatCount == 1) {
1182 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1183 } else {
1184 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1185 }
1186
1187 entry->dispatchInProgress = true;
1188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001189 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191
1192 // Handle case where the policy asked us to try again later last time.
1193 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1194 if (currentTime < entry->interceptKeyWakeupTime) {
1195 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1196 *nextWakeupTime = entry->interceptKeyWakeupTime;
1197 }
1198 return false; // wait until next wakeup
1199 }
1200 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1201 entry->interceptKeyWakeupTime = 0;
1202 }
1203
1204 // Give the policy a chance to intercept the key.
1205 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1206 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001207 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001208 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001209 sp<IBinder> focusedWindowToken =
1210 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1211 if (focusedWindowToken != nullptr) {
1212 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 entry->refCount += 1;
1217 return false; // wait for the command to run
1218 } else {
1219 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1220 }
1221 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001222 if (*dropReason == DropReason::NOT_DROPPED) {
1223 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225 }
1226
1227 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001230 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001232 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 return true;
1234 }
1235
1236 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001237 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1241 return false;
1242 }
1243
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001244 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1246 return true;
1247 }
1248
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001249 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001250 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 // Dispatch the key.
1253 dispatchEventLocked(currentTime, entry, inputTargets);
1254 return true;
1255}
1256
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001259 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1261 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1263 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1264 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#endif
1266}
1267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1269 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001270 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 entry->dispatchInProgress = true;
1274
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001275 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277
1278 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001279 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001281 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 return true;
1284 }
1285
1286 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1287
1288 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001289 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
1291 bool conflictingPointerActions = false;
1292 int32_t injectionResult;
1293 if (isPointerEvent) {
1294 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001296 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 } else {
1299 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001301 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
1303 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1304 return false;
1305 }
1306
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001307 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001308 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1309 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1310 return true;
1311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001313 CancelationOptions::Mode mode(isPointerEvent
1314 ? CancelationOptions::CANCEL_POINTER_EVENTS
1315 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1316 CancelationOptions options(mode, "input event injection failed");
1317 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 return true;
1319 }
1320
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001321 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001324 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001325 std::unordered_map<int32_t, TouchState>::iterator it =
1326 mTouchStatesByDisplay.find(entry->displayId);
1327 if (it != mTouchStatesByDisplay.end()) {
1328 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001329 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001330 // The event has gone through these portal windows, so we add monitoring targets of
1331 // the corresponding displays as well.
1332 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001333 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001334 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001336 }
1337 }
1338 }
1339 }
1340
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Dispatch the motion.
1342 if (conflictingPointerActions) {
1343 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001344 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 synthesizeCancelationEventsForAllConnectionsLocked(options);
1346 }
1347 dispatchEventLocked(currentTime, entry, inputTargets);
1348 return true;
1349}
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001353 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 ", policyFlags=0x%x, "
1355 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1356 "metaState=0x%x, buttonState=0x%x,"
1357 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001358 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1359 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1360 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 "x=%f, y=%f, pressure=%f, size=%f, "
1365 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1366 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001367 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1368 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1369 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1370 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1371 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1372 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1373 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1374 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1375 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1376 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378#endif
1379}
1380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1382 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001383 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384#if DEBUG_DISPATCH_CYCLE
1385 ALOGD("dispatchEventToCurrentInputTargets");
1386#endif
1387
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001388 updateInteractionTokensLocked(*eventEntry, inputTargets);
1389
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001394 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001395 sp<Connection> connection =
1396 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001397 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001398 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001400 if (DEBUG_FOCUS) {
1401 ALOGD("Dropping event delivery to target with channel '%s' because it "
1402 "is no longer registered with the input dispatcher.",
1403 inputTarget.inputChannel->getName().c_str());
1404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 }
1406 }
1407}
1408
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001409void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1410 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1411 // If the policy decides to close the app, we will get a channel removal event via
1412 // unregisterInputChannel, and will clean up the connection that way. We are already not
1413 // sending new pointers to the connection when it blocked, but focused events will continue to
1414 // pile up.
1415 ALOGW("Canceling events for %s because it is unresponsive",
1416 connection->inputChannel->getName().c_str());
1417 if (connection->status == Connection::STATUS_NORMAL) {
1418 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1419 "application not responding");
1420 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 }
1422}
1423
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001424void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001425 if (DEBUG_FOCUS) {
1426 ALOGD("Resetting ANR timeouts.");
1427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428
1429 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001430 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001431 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432}
1433
Tiger Huang721e26f2018-07-24 22:26:19 +08001434/**
1435 * Get the display id that the given event should go to. If this event specifies a valid display id,
1436 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1437 * Focused display is the display that the user most recently interacted with.
1438 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001440 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001441 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001442 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1444 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 break;
1446 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001447 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1449 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 break;
1451 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001453 case EventEntry::Type::CONFIGURATION_CHANGED:
1454 case EventEntry::Type::DEVICE_RESET: {
1455 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 return ADISPLAY_ID_NONE;
1457 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001458 }
1459 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1460}
1461
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001462bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1463 const char* focusedWindowName) {
1464 if (mAnrTracker.empty()) {
1465 // already processed all events that we waited for
1466 mKeyIsWaitingForEventsTimeout = std::nullopt;
1467 return false;
1468 }
1469
1470 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1471 // Start the timer
1472 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1473 "focus to change",
1474 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001475 mKeyIsWaitingForEventsTimeout = currentTime +
1476 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1477 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001478 return true;
1479 }
1480
1481 // We still have pending events, and already started the timer
1482 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1483 return true; // Still waiting
1484 }
1485
1486 // Waited too long, and some connection still hasn't processed all motions
1487 // Just send the key to the focused window
1488 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1489 focusedWindowName);
1490 mKeyIsWaitingForEventsTimeout = std::nullopt;
1491 return false;
1492}
1493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001495 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 std::vector<InputTarget>& inputTargets,
1497 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001498 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499
Tiger Huang721e26f2018-07-24 22:26:19 +08001500 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001501 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001502 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001503 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1504
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 // If there is no currently focused window and no focused application
1506 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001507 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1508 ALOGI("Dropping %s event because there is no focused window or focused application in "
1509 "display %" PRId32 ".",
1510 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001511 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001514 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1515 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1516 // start interacting with another application via touch (app switch). This code can be removed
1517 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1518 // an app is expected to have a focused window.
1519 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1520 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1521 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001522 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1523 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1524 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001525 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001526 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001527 ALOGW("Waiting because no window has focus but %s may eventually add a "
1528 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001529 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001530 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1531 return INPUT_EVENT_INJECTION_PENDING;
1532 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1533 // Already raised ANR. Drop the event
1534 ALOGE("Dropping %s event because there is no focused window",
1535 EventEntry::typeToString(entry.type));
1536 return INPUT_EVENT_INJECTION_FAILED;
1537 } else {
1538 // Still waiting for the focused window
1539 return INPUT_EVENT_INJECTION_PENDING;
1540 }
1541 }
1542
1543 // we have a valid, non-null focused window
1544 resetNoFocusedWindowTimeoutLocked();
1545
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001548 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001551 if (focusedWindowHandle->getInfo()->paused) {
1552 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1553 return INPUT_EVENT_INJECTION_PENDING;
1554 }
1555
1556 // If the event is a key event, then we must wait for all previous events to
1557 // complete before delivering it because previous events may have the
1558 // side-effect of transferring focus to a different window and we want to
1559 // ensure that the following keys are sent to the new window.
1560 //
1561 // Suppose the user touches a button in a window then immediately presses "A".
1562 // If the button causes a pop-up window to appear then we want to ensure that
1563 // the "A" key is delivered to the new pop-up window. This is because users
1564 // often anticipate pending UI changes when typing on a keyboard.
1565 // To obtain this behavior, we must serialize key events with respect to all
1566 // prior input events.
1567 if (entry.type == EventEntry::Type::KEY) {
1568 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1569 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1570 return INPUT_EVENT_INJECTION_PENDING;
1571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573
1574 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001575 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1577 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578
1579 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001580 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581}
1582
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001583/**
1584 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1585 * that are currently unresponsive.
1586 */
1587std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1588 const std::vector<TouchedMonitor>& monitors) const {
1589 std::vector<TouchedMonitor> responsiveMonitors;
1590 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1591 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1592 sp<Connection> connection = getConnectionLocked(
1593 monitor.monitor.inputChannel->getConnectionToken());
1594 if (connection == nullptr) {
1595 ALOGE("Could not find connection for monitor %s",
1596 monitor.monitor.inputChannel->getName().c_str());
1597 return false;
1598 }
1599 if (!connection->responsive) {
1600 ALOGW("Unresponsive monitor %s will not get the new gesture",
1601 connection->inputChannel->getName().c_str());
1602 return false;
1603 }
1604 return true;
1605 });
1606 return responsiveMonitors;
1607}
1608
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 std::vector<InputTarget>& inputTargets,
1612 nsecs_t* nextWakeupTime,
1613 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 enum InjectionPermission {
1616 INJECTION_PERMISSION_UNKNOWN,
1617 INJECTION_PERMISSION_GRANTED,
1618 INJECTION_PERMISSION_DENIED
1619 };
1620
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 // For security reasons, we defer updating the touch state until we are sure that
1622 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 int32_t displayId = entry.displayId;
1624 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1626
1627 // Update the touch state as needed based on the properties of the touch event.
1628 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1629 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001630 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1631 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001633 // Copy current touch state into tempTouchState.
1634 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1635 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001636 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001637 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001638 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1639 mTouchStatesByDisplay.find(displayId);
1640 if (oldStateIt != mTouchStatesByDisplay.end()) {
1641 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001642 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001643 }
1644
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001645 bool isSplit = tempTouchState.split;
1646 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1647 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1648 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1650 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1651 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1652 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1653 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 bool wrongDevice = false;
1656 if (newGesture) {
1657 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001658 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001659 ALOGI("Dropping event because a pointer for a different device is already down "
1660 "in display %" PRId32,
1661 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001662 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1664 switchedDevice = false;
1665 wrongDevice = true;
1666 goto Failed;
1667 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001668 tempTouchState.reset();
1669 tempTouchState.down = down;
1670 tempTouchState.deviceId = entry.deviceId;
1671 tempTouchState.source = entry.source;
1672 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001674 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001675 ALOGI("Dropping move event because a pointer for a different device is already active "
1676 "in display %" PRId32,
1677 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001678 // TODO: test multiple simultaneous input streams.
1679 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1680 switchedDevice = false;
1681 wrongDevice = true;
1682 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1686 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1687
Garfield Tan00f511d2019-06-12 16:55:40 -07001688 int32_t x;
1689 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001691 // Always dispatch mouse events to cursor position.
1692 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 x = int32_t(entry.xCursorPosition);
1694 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001695 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1697 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001698 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001699 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001700 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001701 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1702 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001703
1704 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001705 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 if (newTouchedWindowHandle != nullptr &&
1710 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001711 // New window supports splitting, but we should never split mouse events.
1712 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 } else if (isSplit) {
1714 // New window does not support splitting but we have already split events.
1715 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718
1719 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001722 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 }
1724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1726 ALOGI("Not sending touch event to %s because it is paused",
1727 newTouchedWindowHandle->getName().c_str());
1728 newTouchedWindowHandle = nullptr;
1729 }
1730
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001731 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001733 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1734 if (!isResponsive) {
1735 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1737 newTouchedWindowHandle = nullptr;
1738 }
1739 }
1740
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001741 // Drop events that can't be trusted due to occlusion
1742 if (newTouchedWindowHandle != nullptr &&
1743 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1744 TouchOcclusionInfo occlusionInfo =
1745 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
1746 // The order of the operands in the 'if' below is important because even if the feature
1747 // is not BLOCK we want isTouchTrustedLocked() to execute in order to log details to
1748 // logcat.
1749 if (!isTouchTrustedLocked(occlusionInfo) &&
1750 mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1751 ALOGW("Dropping untrusted touch event due to %s/%d",
1752 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1753 newTouchedWindowHandle = nullptr;
1754 }
1755 }
1756
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 // Also don't send the new touch event to unresponsive gesture monitors
1758 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1759
Michael Wright3dd60e22019-03-27 22:06:44 +00001760 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1761 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 "(%d, %d) in display %" PRId32 ".",
1763 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001764 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1765 goto Failed;
1766 }
1767
1768 if (newTouchedWindowHandle != nullptr) {
1769 // Set target flags.
1770 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1771 if (isSplit) {
1772 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001774 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1775 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1776 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1777 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1778 }
1779
1780 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001781 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1782 newHoverWindowHandle = nullptr;
1783 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001784 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001785 }
1786
1787 // Update the temporary touch state.
1788 BitSet32 pointerIds;
1789 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001791 pointerIds.markBit(pointerId);
1792 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001793 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001796 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 } else {
1798 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1799
1800 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001801 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001802 if (DEBUG_FOCUS) {
1803 ALOGD("Dropping event because the pointer is not down or we previously "
1804 "dropped the pointer down event in display %" PRId32,
1805 displayId);
1806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1808 goto Failed;
1809 }
1810
1811 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1815 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001818 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001819 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1821 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1824 oldTouchedWindowHandle->getName().c_str(),
1825 newTouchedWindowHandle->getName().c_str(), displayId);
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001828 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1829 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1830 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
1832 // Make a slippery entrance into the new window.
1833 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1834 isSplit = true;
1835 }
1836
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 int32_t targetFlags =
1838 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 if (isSplit) {
1840 targetFlags |= InputTarget::FLAG_SPLIT;
1841 }
1842 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1843 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1844 }
1845
1846 BitSet32 pointerIds;
1847 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001848 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852 }
1853 }
1854
1855 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001856 // Let the previous window know that the hover sequence is over, unless we already did it
1857 // when dispatching it as is to newTouchedWindowHandle.
1858 if (mLastHoverWindowHandle != nullptr &&
1859 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1860 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861#if DEBUG_HOVER
1862 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1866 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
1868
Garfield Tandf26e862020-07-01 20:18:19 -07001869 // Let the new window know that the hover sequence is starting, unless we already did it
1870 // when dispatching it as is to newTouchedWindowHandle.
1871 if (newHoverWindowHandle != nullptr &&
1872 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1873 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874#if DEBUG_HOVER
1875 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001876 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001878 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1879 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1880 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882 }
1883
1884 // Check permission to inject into all touched foreground windows and ensure there
1885 // is at least one touched foreground window.
1886 {
1887 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1890 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1893 injectionPermission = INJECTION_PERMISSION_DENIED;
1894 goto Failed;
1895 }
1896 }
1897 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001899 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001900 ALOGI("Dropping event because there is no touched foreground window in display "
1901 "%" PRId32 " or gesture monitor to receive it.",
1902 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1904 goto Failed;
1905 }
1906
1907 // Permission granted to injection into all touched foreground windows.
1908 injectionPermission = INJECTION_PERMISSION_GRANTED;
1909 }
1910
1911 // Check whether windows listening for outside touches are owned by the same UID. If it is
1912 // set the policy flag that we will not reveal coordinate information to this window.
1913 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1914 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 if (foregroundWindowHandle) {
1917 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001919 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1920 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1921 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1923 InputTarget::FLAG_ZERO_COORDS,
1924 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927 }
1928 }
1929 }
1930
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 // If this is the first pointer going down and the touched window has a wallpaper
1932 // then also add the touched wallpaper windows so they are locked in for the duration
1933 // of the touch gesture.
1934 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1935 // engine only supports touch events. We would need to add a mechanism similar
1936 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1937 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1938 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001940 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001941 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001942 getWindowHandlesLocked(displayId);
1943 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001945 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001946 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001948 .addOrUpdateWindow(windowHandle,
1949 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1950 InputTarget::
1951 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1952 InputTarget::FLAG_DISPATCH_AS_IS,
1953 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
1955 }
1956 }
1957 }
1958
1959 // Success! Output targets.
1960 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1961
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001967 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001968 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 }
1971
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // Drop the outside or hover touch windows since we will not care about them
1973 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975
1976Failed:
1977 // Check injection permission once and for all.
1978 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001979 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 injectionPermission = INJECTION_PERMISSION_GRANTED;
1981 } else {
1982 injectionPermission = INJECTION_PERMISSION_DENIED;
1983 }
1984 }
1985
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1987 return injectionResult;
1988 }
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 if (!wrongDevice) {
1992 if (switchedDevice) {
1993 if (DEBUG_FOCUS) {
1994 ALOGD("Conflicting pointer actions: Switched to a different device.");
1995 }
1996 *outConflictingPointerActions = true;
1997 }
1998
1999 if (isHoverAction) {
2000 // Started hovering, therefore no longer down.
2001 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002002 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002003 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2004 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 *outConflictingPointerActions = true;
2007 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002008 tempTouchState.reset();
2009 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2010 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2011 tempTouchState.deviceId = entry.deviceId;
2012 tempTouchState.source = entry.source;
2013 tempTouchState.displayId = displayId;
2014 }
2015 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2016 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2017 // All pointers up or canceled.
2018 tempTouchState.reset();
2019 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2020 // First pointer went down.
2021 if (oldState && oldState->down) {
2022 if (DEBUG_FOCUS) {
2023 ALOGD("Conflicting pointer actions: Down received while already down.");
2024 }
2025 *outConflictingPointerActions = true;
2026 }
2027 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2028 // One pointer went up.
2029 if (isSplit) {
2030 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2031 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002033 for (size_t i = 0; i < tempTouchState.windows.size();) {
2034 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2035 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2036 touchedWindow.pointerIds.clearBit(pointerId);
2037 if (touchedWindow.pointerIds.isEmpty()) {
2038 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2039 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002042 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002044 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002045 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002046
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002047 // Save changes unless the action was scroll in which case the temporary touch
2048 // state was only valid for this one action.
2049 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2050 if (tempTouchState.displayId >= 0) {
2051 mTouchStatesByDisplay[displayId] = tempTouchState;
2052 } else {
2053 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002057 // Update hover state.
2058 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 }
2060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 return injectionResult;
2062}
2063
2064void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002065 int32_t targetFlags, BitSet32 pointerIds,
2066 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002067 std::vector<InputTarget>::iterator it =
2068 std::find_if(inputTargets.begin(), inputTargets.end(),
2069 [&windowHandle](const InputTarget& inputTarget) {
2070 return inputTarget.inputChannel->getConnectionToken() ==
2071 windowHandle->getToken();
2072 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002073
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002074 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002075
2076 if (it == inputTargets.end()) {
2077 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002078 std::shared_ptr<InputChannel> inputChannel =
2079 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002080 if (inputChannel == nullptr) {
2081 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2082 return;
2083 }
2084 inputTarget.inputChannel = inputChannel;
2085 inputTarget.flags = targetFlags;
2086 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2087 inputTargets.push_back(inputTarget);
2088 it = inputTargets.end() - 1;
2089 }
2090
2091 ALOG_ASSERT(it->flags == targetFlags);
2092 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2093
chaviw1ff3d1e2020-07-01 15:53:47 -07002094 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095}
2096
Michael Wright3dd60e22019-03-27 22:06:44 +00002097void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 int32_t displayId, float xOffset,
2099 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2101 mGlobalMonitorsByDisplay.find(displayId);
2102
2103 if (it != mGlobalMonitorsByDisplay.end()) {
2104 const std::vector<Monitor>& monitors = it->second;
2105 for (const Monitor& monitor : monitors) {
2106 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
2109}
2110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002111void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2112 float yOffset,
2113 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002114 InputTarget target;
2115 target.inputChannel = monitor.inputChannel;
2116 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002117 ui::Transform t;
2118 t.set(xOffset, yOffset);
2119 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002120 inputTargets.push_back(target);
2121}
2122
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 const InjectionState* injectionState) {
2125 if (injectionState &&
2126 (windowHandle == nullptr ||
2127 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2128 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002129 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 "owned by uid %d",
2132 injectionState->injectorPid, injectionState->injectorUid,
2133 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 } else {
2135 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138 return false;
2139 }
2140 return true;
2141}
2142
Robert Carrc9bf1d32020-04-13 17:21:08 -07002143/**
2144 * Indicate whether one window handle should be considered as obscuring
2145 * another window handle. We only check a few preconditions. Actually
2146 * checking the bounds is left to the caller.
2147 */
2148static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2149 const sp<InputWindowHandle>& otherHandle) {
2150 // Compare by token so cloned layers aren't counted
2151 if (haveSameToken(windowHandle, otherHandle)) {
2152 return false;
2153 }
2154 auto info = windowHandle->getInfo();
2155 auto otherInfo = otherHandle->getInfo();
2156 if (!otherInfo->visible) {
2157 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002158 } else if (info->ownerUid == otherInfo->ownerUid) {
2159 // If ownerUid is the same we don't generate occlusion events as there
2160 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002161 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002162 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002163 return false;
2164 } else if (otherInfo->displayId != info->displayId) {
2165 return false;
2166 }
2167 return true;
2168}
2169
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002170/**
2171 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2172 * untrusted, one should check:
2173 *
2174 * 1. If result.hasBlockingOcclusion is true.
2175 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2176 * BLOCK_UNTRUSTED.
2177 *
2178 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2179 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2180 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2181 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2182 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2183 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2184 *
2185 * If neither of those is true, then it means the touch can be allowed.
2186 */
2187InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2188 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2189 int32_t displayId = windowHandle->getInfo()->displayId;
2190 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2191 TouchOcclusionInfo info;
2192 info.hasBlockingOcclusion = false;
2193 info.obscuringOpacity = 0;
2194 info.obscuringUid = -1;
2195 std::map<int32_t, float> opacityByUid;
2196 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2197 if (windowHandle == otherHandle) {
2198 break; // All future windows are below us. Exit early.
2199 }
2200 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2201 if (canBeObscuredBy(windowHandle, otherHandle) &&
2202 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2203 otherInfo->frameContainsPoint(x, y)) {
2204 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2205 // we perform the checks below to see if the touch can be propagated or not based on the
2206 // window's touch occlusion mode
2207 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2208 info.hasBlockingOcclusion = true;
2209 info.obscuringUid = otherInfo->ownerUid;
2210 info.obscuringPackage = otherInfo->packageName;
2211 break;
2212 }
2213 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2214 uint32_t uid = otherInfo->ownerUid;
2215 float opacity =
2216 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2217 // Given windows A and B:
2218 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2219 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2220 opacityByUid[uid] = opacity;
2221 if (opacity > info.obscuringOpacity) {
2222 info.obscuringOpacity = opacity;
2223 info.obscuringUid = uid;
2224 info.obscuringPackage = otherInfo->packageName;
2225 }
2226 }
2227 }
2228 }
2229 return info;
2230}
2231
2232bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2233 if (occlusionInfo.hasBlockingOcclusion) {
2234 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2235 occlusionInfo.obscuringUid);
2236 return false;
2237 }
2238 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2239 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2240 "%.2f, maximum allowed = %.2f)",
2241 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2242 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2243 return false;
2244 }
2245 return true;
2246}
2247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2249 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002251 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002252 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002253 if (windowHandle == otherHandle) {
2254 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002257 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002258 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 return true;
2260 }
2261 }
2262 return false;
2263}
2264
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002265bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2266 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002267 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002268 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002269 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002270 if (windowHandle == otherHandle) {
2271 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002272 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002273 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002274 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002275 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002276 return true;
2277 }
2278 }
2279 return false;
2280}
2281
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002282std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002283 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002285 if (applicationHandle != nullptr) {
2286 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002287 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 } else {
2289 return applicationHandle->getName();
2290 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002291 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002292 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002294 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296}
2297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002298void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002299 if (eventEntry.type == EventEntry::Type::FOCUS) {
2300 // Focus events are passed to apps, but do not represent user activity.
2301 return;
2302 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002303 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002304 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002305 if (focusedWindowHandle != nullptr) {
2306 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002307 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002309 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310#endif
2311 return;
2312 }
2313 }
2314
2315 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002316 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002317 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002318 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2319 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320 return;
2321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002323 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 eventType = USER_ACTIVITY_EVENT_TOUCH;
2325 }
2326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002328 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002329 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2330 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 return;
2332 }
2333 eventType = USER_ACTIVITY_EVENT_BUTTON;
2334 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002336 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002337 case EventEntry::Type::CONFIGURATION_CHANGED:
2338 case EventEntry::Type::DEVICE_RESET: {
2339 LOG_ALWAYS_FATAL("%s events are not user activity",
2340 EventEntry::typeToString(eventEntry.type));
2341 break;
2342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002345 std::unique_ptr<CommandEntry> commandEntry =
2346 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002347 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002349 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350}
2351
2352void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 const sp<Connection>& connection,
2354 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002355 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002356 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002358 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002359 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002360 ATRACE_NAME(message.c_str());
2361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362#if DEBUG_DISPATCH_CYCLE
2363 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002364 "globalScaleFactor=%f, pointerIds=0x%x %s",
2365 connection->getInputChannelName().c_str(), inputTarget.flags,
2366 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2367 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
2369
2370 // Skip this event if the connection status is not normal.
2371 // We don't want to enqueue additional outbound events if the connection is broken.
2372 if (connection->status != Connection::STATUS_NORMAL) {
2373#if DEBUG_DISPATCH_CYCLE
2374 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376#endif
2377 return;
2378 }
2379
2380 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002381 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2382 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2383 "Entry type %s should not have FLAG_SPLIT",
2384 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002386 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002387 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002389 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 if (!splitMotionEntry) {
2391 return; // split event was dropped
2392 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002393 if (DEBUG_FOCUS) {
2394 ALOGD("channel '%s' ~ Split motion event.",
2395 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002396 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002397 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 splitMotionEntry->release();
2400 return;
2401 }
2402 }
2403
2404 // Not splitting. Enqueue dispatch entries for the event as is.
2405 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2406}
2407
2408void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002409 const sp<Connection>& connection,
2410 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002411 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002412 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002414 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002415 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 ATRACE_NAME(message.c_str());
2417 }
2418
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002419 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
2421 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002422 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002424 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002425 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002426 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002428 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002430 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002432 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434
2435 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002436 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 startDispatchCycleLocked(currentTime, connection);
2438 }
2439}
2440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002441void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2442 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002443 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002444 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002445 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002446 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2447 connection->getInputChannelName().c_str(),
2448 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002449 ATRACE_NAME(message.c_str());
2450 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002451 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 if (!(inputTargetFlags & dispatchMode)) {
2453 return;
2454 }
2455 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2456
2457 // This is a new event.
2458 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002459 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002460 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002462 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2463 // different EventEntry than what was passed in.
2464 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002466 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002467 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002468 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002469 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002470 dispatchEntry->resolvedAction = keyEntry.action;
2471 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2474 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2477 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479 return; // skip the inconsistent event
2480 }
2481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002484 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002485 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002486 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2487 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2488 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2489 static_cast<int32_t>(IdGenerator::Source::OTHER);
2490 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2492 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2493 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2494 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2495 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2496 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2497 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2498 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2499 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2500 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2501 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002502 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002503 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 }
2505 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002506 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2507 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2510 "event",
2511 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002516 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2518 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2519 }
2520 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2521 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2525 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2528 "event",
2529 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 return; // skip the inconsistent event
2532 }
2533
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002534 dispatchEntry->resolvedEventId =
2535 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2536 ? mIdGenerator.nextId()
2537 : motionEntry.id;
2538 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2539 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2540 ") to MotionEvent(id=0x%" PRIx32 ").",
2541 motionEntry.id, dispatchEntry->resolvedEventId);
2542 ATRACE_NAME(message.c_str());
2543 }
2544
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002545 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002546 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547
2548 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002550 case EventEntry::Type::FOCUS: {
2551 break;
2552 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002553 case EventEntry::Type::CONFIGURATION_CHANGED:
2554 case EventEntry::Type::DEVICE_RESET: {
2555 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002556 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002557 break;
2558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560
2561 // Remember that we are waiting for this dispatch to complete.
2562 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002563 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565
2566 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002567 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002568 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002569}
2570
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002571/**
2572 * This function is purely for debugging. It helps us understand where the user interaction
2573 * was taking place. For example, if user is touching launcher, we will see a log that user
2574 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2575 * We will see both launcher and wallpaper in that list.
2576 * Once the interaction with a particular set of connections starts, no new logs will be printed
2577 * until the set of interacted connections changes.
2578 *
2579 * The following items are skipped, to reduce the logspam:
2580 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2581 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2582 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2583 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2584 * Both of those ACTION_UP events would not be logged
2585 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2586 * will not be logged. This is omitted to reduce the amount of data printed.
2587 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2588 * gesture monitor is the only connection receiving the remainder of the gesture.
2589 */
2590void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2591 const std::vector<InputTarget>& targets) {
2592 // Skip ACTION_UP events, and all events other than keys and motions
2593 if (entry.type == EventEntry::Type::KEY) {
2594 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2595 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2596 return;
2597 }
2598 } else if (entry.type == EventEntry::Type::MOTION) {
2599 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2600 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2601 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2602 return;
2603 }
2604 } else {
2605 return; // Not a key or a motion
2606 }
2607
2608 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2609 std::vector<sp<Connection>> newConnections;
2610 for (const InputTarget& target : targets) {
2611 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2612 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2613 continue; // Skip windows that receive ACTION_OUTSIDE
2614 }
2615
2616 sp<IBinder> token = target.inputChannel->getConnectionToken();
2617 sp<Connection> connection = getConnectionLocked(token);
2618 if (connection == nullptr || connection->monitor) {
2619 continue; // We only need to keep track of the non-monitor connections.
2620 }
2621 newConnectionTokens.insert(std::move(token));
2622 newConnections.emplace_back(connection);
2623 }
2624 if (newConnectionTokens == mInteractionConnectionTokens) {
2625 return; // no change
2626 }
2627 mInteractionConnectionTokens = newConnectionTokens;
2628
2629 std::string windowList;
2630 for (const sp<Connection>& connection : newConnections) {
2631 windowList += connection->getWindowName() + ", ";
2632 }
2633 std::string message = "Interaction with windows: " + windowList;
2634 if (windowList.empty()) {
2635 message += "<none>";
2636 }
2637 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2638}
2639
chaviwfd6d3512019-03-25 13:23:49 -07002640void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002641 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002642 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002643 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2644 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002645 return;
2646 }
2647
Vishnu Nairad321cd2020-08-20 16:40:21 -07002648 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2649 if (focusedToken == token) {
2650 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002651 return;
2652 }
2653
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002654 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2655 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002656 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002657 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658}
2659
2660void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002662 if (ATRACE_ENABLED()) {
2663 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002665 ATRACE_NAME(message.c_str());
2666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669#endif
2670
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002671 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2672 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002674 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002675 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002676 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677
2678 // Publish the event.
2679 status_t status;
2680 EventEntry* eventEntry = dispatchEntry->eventEntry;
2681 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002682 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002683 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2684 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002686 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002687 status =
2688 connection->inputPublisher
2689 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2690 keyEntry->deviceId, keyEntry->source,
2691 keyEntry->displayId, std::move(hmac),
2692 dispatchEntry->resolvedAction,
2693 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2694 keyEntry->scanCode, keyEntry->metaState,
2695 keyEntry->repeatCount, keyEntry->downTime,
2696 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002700 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703 PointerCoords scaledCoords[MAX_POINTERS];
2704 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2705
chaviw82357092020-01-28 13:13:06 -08002706 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2708 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2709 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002710 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2712 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002713 // Don't apply window scale here since we don't want scale to affect raw
2714 // coordinates. The scale will be sent back to the client and applied
2715 // later when requesting relative coordinates.
2716 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2717 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 }
2719 usingCoords = scaledCoords;
2720 }
2721 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 // We don't want the dispatch target to know.
2723 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2724 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2725 scaledCoords[i].clear();
2726 }
2727 usingCoords = scaledCoords;
2728 }
2729 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002730
2731 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732
2733 // Publish the motion event.
2734 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002735 .publishMotionEvent(dispatchEntry->seq,
2736 dispatchEntry->resolvedEventId,
2737 motionEntry->deviceId, motionEntry->source,
2738 motionEntry->displayId, std::move(hmac),
2739 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 motionEntry->actionButton,
2741 dispatchEntry->resolvedFlags,
2742 motionEntry->edgeFlags, motionEntry->metaState,
2743 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002744 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002745 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002746 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 motionEntry->yPrecision,
2748 motionEntry->xCursorPosition,
2749 motionEntry->yCursorPosition,
2750 motionEntry->downTime, motionEntry->eventTime,
2751 motionEntry->pointerCount,
2752 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002753 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002754 break;
2755 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002756 case EventEntry::Type::FOCUS: {
2757 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2758 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002759 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002760 focusEntry->hasFocus,
2761 mInTouchMode);
2762 break;
2763 }
2764
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002765 case EventEntry::Type::CONFIGURATION_CHANGED:
2766 case EventEntry::Type::DEVICE_RESET: {
2767 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2768 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
2772
2773 // Check the result.
2774 if (status) {
2775 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002776 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 "This is unexpected because the wait queue is empty, so the pipe "
2779 "should be empty and we shouldn't have any problems writing an "
2780 "event to it, status=%d",
2781 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2783 } else {
2784 // Pipe is full and we are waiting for the app to finish process some events
2785 // before sending more events to it.
2786#if DEBUG_DISPATCH_CYCLE
2787 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788 "waiting for the application to catch up",
2789 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 }
2792 } else {
2793 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 "status=%d",
2795 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2797 }
2798 return;
2799 }
2800
2801 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002802 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2803 connection->outboundQueue.end(),
2804 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002805 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002806 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002807 if (connection->responsive) {
2808 mAnrTracker.insert(dispatchEntry->timeoutTime,
2809 connection->inputChannel->getConnectionToken());
2810 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002811 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813}
2814
chaviw09c8d2d2020-08-24 15:48:26 -07002815std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2816 size_t size;
2817 switch (event.type) {
2818 case VerifiedInputEvent::Type::KEY: {
2819 size = sizeof(VerifiedKeyEvent);
2820 break;
2821 }
2822 case VerifiedInputEvent::Type::MOTION: {
2823 size = sizeof(VerifiedMotionEvent);
2824 break;
2825 }
2826 }
2827 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2828 return mHmacKeyManager.sign(start, size);
2829}
2830
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002831const std::array<uint8_t, 32> InputDispatcher::getSignature(
2832 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2833 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2834 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2835 // Only sign events up and down events as the purely move events
2836 // are tied to their up/down counterparts so signing would be redundant.
2837 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2838 verifiedEvent.actionMasked = actionMasked;
2839 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002840 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002841 }
2842 return INVALID_HMAC;
2843}
2844
2845const std::array<uint8_t, 32> InputDispatcher::getSignature(
2846 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2847 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2848 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2849 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002850 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002851}
2852
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 const sp<Connection>& connection, uint32_t seq,
2855 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856#if DEBUG_DISPATCH_CYCLE
2857 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002858 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859#endif
2860
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 if (connection->status == Connection::STATUS_BROKEN ||
2862 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 return;
2864 }
2865
2866 // Notify other system components and prepare to start the next dispatch cycle.
2867 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2868}
2869
2870void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 const sp<Connection>& connection,
2872 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873#if DEBUG_DISPATCH_CYCLE
2874 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876#endif
2877
2878 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002879 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002880 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002881 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002882 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
2884 // The connection appears to be unrecoverably broken.
2885 // Ignore already broken or zombie connections.
2886 if (connection->status == Connection::STATUS_NORMAL) {
2887 connection->status = Connection::STATUS_BROKEN;
2888
2889 if (notify) {
2890 // Notify other system components.
2891 onDispatchCycleBrokenLocked(currentTime, connection);
2892 }
2893 }
2894}
2895
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002896void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2897 while (!queue.empty()) {
2898 DispatchEntry* dispatchEntry = queue.front();
2899 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002900 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
2902}
2903
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002904void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002906 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
2908 delete dispatchEntry;
2909}
2910
2911int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2912 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2913
2914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002915 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002917 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 "fd=%d, events=0x%x",
2920 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return 0; // remove the callback
2922 }
2923
2924 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002925 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2927 if (!(events & ALOOPER_EVENT_INPUT)) {
2928 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 "events=0x%x",
2930 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 return 1;
2932 }
2933
2934 nsecs_t currentTime = now();
2935 bool gotOne = false;
2936 status_t status;
2937 for (;;) {
2938 uint32_t seq;
2939 bool handled;
2940 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2941 if (status) {
2942 break;
2943 }
2944 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2945 gotOne = true;
2946 }
2947 if (gotOne) {
2948 d->runCommandsLockedInterruptible();
2949 if (status == WOULD_BLOCK) {
2950 return 1;
2951 }
2952 }
2953
2954 notify = status != DEAD_OBJECT || !connection->monitor;
2955 if (notify) {
2956 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
2959 } else {
2960 // Monitor channels are never explicitly unregistered.
2961 // We do it automatically when the remote endpoint is closed so don't warn
2962 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002963 const bool stillHaveWindowHandle =
2964 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2965 nullptr;
2966 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 if (notify) {
2968 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 "events=0x%x",
2970 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 }
2972 }
2973
Garfield Tan15601662020-09-22 15:32:38 -07002974 // Remove the channel.
2975 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978}
2979
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002982 for (const auto& pair : mConnectionsByFd) {
2983 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985}
2986
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002988 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002989 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2990 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2991}
2992
2993void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2994 const CancelationOptions& options,
2995 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2996 for (const auto& it : monitorsByDisplay) {
2997 const std::vector<Monitor>& monitors = it.second;
2998 for (const Monitor& monitor : monitors) {
2999 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003000 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003001 }
3002}
3003
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003005 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003006 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003007 if (connection == nullptr) {
3008 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003010
3011 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012}
3013
3014void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3015 const sp<Connection>& connection, const CancelationOptions& options) {
3016 if (connection->status == Connection::STATUS_BROKEN) {
3017 return;
3018 }
3019
3020 nsecs_t currentTime = now();
3021
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003022 std::vector<EventEntry*> cancelationEvents =
3023 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003025 if (cancelationEvents.empty()) {
3026 return;
3027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003029 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3030 "with reality: %s, mode=%d.",
3031 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3032 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003034
3035 InputTarget target;
3036 sp<InputWindowHandle> windowHandle =
3037 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3038 if (windowHandle != nullptr) {
3039 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003040 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003041 target.globalScaleFactor = windowInfo->globalScaleFactor;
3042 }
3043 target.inputChannel = connection->inputChannel;
3044 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3045
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003046 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3047 EventEntry* cancelationEventEntry = cancelationEvents[i];
3048 switch (cancelationEventEntry->type) {
3049 case EventEntry::Type::KEY: {
3050 logOutboundKeyDetails("cancel - ",
3051 static_cast<const KeyEntry&>(*cancelationEventEntry));
3052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003054 case EventEntry::Type::MOTION: {
3055 logOutboundMotionDetails("cancel - ",
3056 static_cast<const MotionEntry&>(*cancelationEventEntry));
3057 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003059 case EventEntry::Type::FOCUS: {
3060 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3061 break;
3062 }
3063 case EventEntry::Type::CONFIGURATION_CHANGED:
3064 case EventEntry::Type::DEVICE_RESET: {
3065 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3066 EventEntry::typeToString(cancelationEventEntry->type));
3067 break;
3068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 }
3070
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003071 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3072 target, InputTarget::FLAG_DISPATCH_AS_IS);
3073
3074 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003076
3077 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078}
3079
Svet Ganov5d3bc372020-01-26 23:11:07 -08003080void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3081 const sp<Connection>& connection) {
3082 if (connection->status == Connection::STATUS_BROKEN) {
3083 return;
3084 }
3085
3086 nsecs_t currentTime = now();
3087
3088 std::vector<EventEntry*> downEvents =
3089 connection->inputState.synthesizePointerDownEvents(currentTime);
3090
3091 if (downEvents.empty()) {
3092 return;
3093 }
3094
3095#if DEBUG_OUTBOUND_EVENT_DETAILS
3096 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3097 connection->getInputChannelName().c_str(), downEvents.size());
3098#endif
3099
3100 InputTarget target;
3101 sp<InputWindowHandle> windowHandle =
3102 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3103 if (windowHandle != nullptr) {
3104 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003105 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003106 target.globalScaleFactor = windowInfo->globalScaleFactor;
3107 }
3108 target.inputChannel = connection->inputChannel;
3109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3110
3111 for (EventEntry* downEventEntry : downEvents) {
3112 switch (downEventEntry->type) {
3113 case EventEntry::Type::MOTION: {
3114 logOutboundMotionDetails("down - ",
3115 static_cast<const MotionEntry&>(*downEventEntry));
3116 break;
3117 }
3118
3119 case EventEntry::Type::KEY:
3120 case EventEntry::Type::FOCUS:
3121 case EventEntry::Type::CONFIGURATION_CHANGED:
3122 case EventEntry::Type::DEVICE_RESET: {
3123 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3124 EventEntry::typeToString(downEventEntry->type));
3125 break;
3126 }
3127 }
3128
3129 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3130 target, InputTarget::FLAG_DISPATCH_AS_IS);
3131
3132 downEventEntry->release();
3133 }
3134
3135 startDispatchCycleLocked(currentTime, connection);
3136}
3137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003139 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 ALOG_ASSERT(pointerIds.value != 0);
3141
3142 uint32_t splitPointerIndexMap[MAX_POINTERS];
3143 PointerProperties splitPointerProperties[MAX_POINTERS];
3144 PointerCoords splitPointerCoords[MAX_POINTERS];
3145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003146 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 uint32_t splitPointerCount = 0;
3148
3149 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 uint32_t pointerId = uint32_t(pointerProperties.id);
3154 if (pointerIds.hasBit(pointerId)) {
3155 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3156 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3157 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003158 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 splitPointerCount += 1;
3160 }
3161 }
3162
3163 if (splitPointerCount != pointerIds.count()) {
3164 // This is bad. We are missing some of the pointers that we expected to deliver.
3165 // Most likely this indicates that we received an ACTION_MOVE events that has
3166 // different pointer ids than we expected based on the previous ACTION_DOWN
3167 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3168 // in this way.
3169 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 "we expected there to be %d pointers. This probably means we received "
3171 "a broken sequence of pointer ids from the input device.",
3172 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003173 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
3175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3179 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3181 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 uint32_t pointerId = uint32_t(pointerProperties.id);
3184 if (pointerIds.hasBit(pointerId)) {
3185 if (pointerIds.count() == 1) {
3186 // The first/last pointer went down/up.
3187 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 ? AMOTION_EVENT_ACTION_DOWN
3189 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 } else {
3191 // A secondary pointer went down/up.
3192 uint32_t splitPointerIndex = 0;
3193 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3194 splitPointerIndex += 1;
3195 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 action = maskedAction |
3197 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199 } else {
3200 // An unrelated pointer changed.
3201 action = AMOTION_EVENT_ACTION_MOVE;
3202 }
3203 }
3204
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003205 int32_t newId = mIdGenerator.nextId();
3206 if (ATRACE_ENABLED()) {
3207 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3208 ") to MotionEvent(id=0x%" PRIx32 ").",
3209 originalMotionEntry.id, newId);
3210 ATRACE_NAME(message.c_str());
3211 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003212 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003213 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3214 originalMotionEntry.source, originalMotionEntry.displayId,
3215 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 originalMotionEntry.actionButton, originalMotionEntry.flags,
3217 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3218 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3219 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3220 originalMotionEntry.xCursorPosition,
3221 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003222 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003224 if (originalMotionEntry.injectionState) {
3225 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 splitMotionEntry->injectionState->refCount += 1;
3227 }
3228
3229 return splitMotionEntry;
3230}
3231
3232void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3233#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003234 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235#endif
3236
3237 bool needWake;
3238 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003239 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240
Prabir Pradhan42611e02018-11-27 14:04:02 -08003241 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003242 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 needWake = enqueueInboundEventLocked(newEntry);
3244 } // release lock
3245
3246 if (needWake) {
3247 mLooper->wake();
3248 }
3249}
3250
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003251/**
3252 * If one of the meta shortcuts is detected, process them here:
3253 * Meta + Backspace -> generate BACK
3254 * Meta + Enter -> generate HOME
3255 * This will potentially overwrite keyCode and metaState.
3256 */
3257void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003259 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3260 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3261 if (keyCode == AKEYCODE_DEL) {
3262 newKeyCode = AKEYCODE_BACK;
3263 } else if (keyCode == AKEYCODE_ENTER) {
3264 newKeyCode = AKEYCODE_HOME;
3265 }
3266 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003267 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003268 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003269 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003270 keyCode = newKeyCode;
3271 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3272 }
3273 } else if (action == AKEY_EVENT_ACTION_UP) {
3274 // In order to maintain a consistent stream of up and down events, check to see if the key
3275 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3276 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003277 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003278 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003279 auto replacementIt = mReplacedKeys.find(replacement);
3280 if (replacementIt != mReplacedKeys.end()) {
3281 keyCode = replacementIt->second;
3282 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003283 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3284 }
3285 }
3286}
3287
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3289#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3291 "policyFlags=0x%x, action=0x%x, "
3292 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3293 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3294 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3295 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296#endif
3297 if (!validateKeyEvent(args->action)) {
3298 return;
3299 }
3300
3301 uint32_t policyFlags = args->policyFlags;
3302 int32_t flags = args->flags;
3303 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003304 // InputDispatcher tracks and generates key repeats on behalf of
3305 // whatever notifies it, so repeatCount should always be set to 0
3306 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3308 policyFlags |= POLICY_FLAG_VIRTUAL;
3309 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 if (policyFlags & POLICY_FLAG_FUNCTION) {
3312 metaState |= AMETA_FUNCTION_ON;
3313 }
3314
3315 policyFlags |= POLICY_FLAG_TRUSTED;
3316
Michael Wright78f24442014-08-06 15:55:28 -07003317 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003318 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003319
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003321 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003322 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3323 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Michael Wright2b3c3302018-03-02 17:19:13 +00003325 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003327 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3328 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 bool needWake;
3333 { // acquire lock
3334 mLock.lock();
3335
3336 if (shouldSendKeyToInputFilterLocked(args)) {
3337 mLock.unlock();
3338
3339 policyFlags |= POLICY_FLAG_FILTERED;
3340 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3341 return; // event was consumed by the filter
3342 }
3343
3344 mLock.lock();
3345 }
3346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003348 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 args->displayId, policyFlags, args->action, flags, keyCode,
3350 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
3352 needWake = enqueueInboundEventLocked(newEntry);
3353 mLock.unlock();
3354 } // release lock
3355
3356 if (needWake) {
3357 mLooper->wake();
3358 }
3359}
3360
3361bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3362 return mInputFilterEnabled;
3363}
3364
3365void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3366#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003367 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3368 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003369 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3370 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003371 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003372 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3373 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3374 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3375 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 for (uint32_t i = 0; i < args->pointerCount; i++) {
3377 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 "x=%f, y=%f, pressure=%f, size=%f, "
3379 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3380 "orientation=%f",
3381 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3382 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3383 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3384 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3385 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3386 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3387 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3388 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3389 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3390 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
3392#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003393 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3394 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 return;
3396 }
3397
3398 uint32_t policyFlags = args->policyFlags;
3399 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003400
3401 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003402 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003403 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3404 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
3408 bool needWake;
3409 { // acquire lock
3410 mLock.lock();
3411
3412 if (shouldSendMotionToInputFilterLocked(args)) {
3413 mLock.unlock();
3414
3415 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003416 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003417 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3418 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003419 args->metaState, args->buttonState, args->classification, transform,
3420 args->xPrecision, args->yPrecision, args->xCursorPosition,
3421 args->yCursorPosition, args->downTime, args->eventTime,
3422 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
3424 policyFlags |= POLICY_FLAG_FILTERED;
3425 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3426 return; // event was consumed by the filter
3427 }
3428
3429 mLock.lock();
3430 }
3431
3432 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003433 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003434 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003435 args->displayId, policyFlags, args->action, args->actionButton,
3436 args->flags, args->metaState, args->buttonState,
3437 args->classification, args->edgeFlags, args->xPrecision,
3438 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3439 args->downTime, args->pointerCount, args->pointerProperties,
3440 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441
3442 needWake = enqueueInboundEventLocked(newEntry);
3443 mLock.unlock();
3444 } // release lock
3445
3446 if (needWake) {
3447 mLooper->wake();
3448 }
3449}
3450
3451bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003452 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453}
3454
3455void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3456#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003457 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 "switchMask=0x%08x",
3459 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460#endif
3461
3462 uint32_t policyFlags = args->policyFlags;
3463 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465}
3466
3467void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3468#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3470 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471#endif
3472
3473 bool needWake;
3474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003475 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
Prabir Pradhan42611e02018-11-27 14:04:02 -08003477 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003478 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 needWake = enqueueInboundEventLocked(newEntry);
3480 } // release lock
3481
3482 if (needWake) {
3483 mLooper->wake();
3484 }
3485}
3486
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3488 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003489 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490#if DEBUG_INBOUND_EVENT_DETAILS
3491 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003492 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3493 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003495 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 policyFlags |= POLICY_FLAG_INJECTED;
3498 if (hasInjectionPermission(injectorPid, injectorUid)) {
3499 policyFlags |= POLICY_FLAG_TRUSTED;
3500 }
3501
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003502 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003505 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3506 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 if (!validateKeyEvent(action)) {
3508 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003511 int32_t flags = incomingKey.getFlags();
3512 int32_t keyCode = incomingKey.getKeyCode();
3513 int32_t metaState = incomingKey.getMetaState();
3514 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003516 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003517 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003518 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3519 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3520 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3523 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003524 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525
3526 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3527 android::base::Timer t;
3528 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3529 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3530 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3531 std::to_string(t.duration().count()).c_str());
3532 }
3533 }
3534
3535 mLock.lock();
3536 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003537 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3538 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003539 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3540 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003541 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003542 injectedEntries.push(injectedEntry);
3543 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003546 case AINPUT_EVENT_TYPE_MOTION: {
3547 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3548 int32_t action = motionEvent->getAction();
3549 size_t pointerCount = motionEvent->getPointerCount();
3550 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3551 int32_t actionButton = motionEvent->getActionButton();
3552 int32_t displayId = motionEvent->getDisplayId();
3553 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3554 return INPUT_EVENT_INJECTION_FAILED;
3555 }
3556
3557 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3558 nsecs_t eventTime = motionEvent->getEventTime();
3559 android::base::Timer t;
3560 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3561 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3562 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3563 std::to_string(t.duration().count()).c_str());
3564 }
3565 }
3566
3567 mLock.lock();
3568 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3569 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3570 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003571 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3572 motionEvent->getSource(), motionEvent->getDisplayId(),
3573 policyFlags, action, actionButton, motionEvent->getFlags(),
3574 motionEvent->getMetaState(), motionEvent->getButtonState(),
3575 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3576 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003577 motionEvent->getRawXCursorPosition(),
3578 motionEvent->getRawYCursorPosition(),
3579 motionEvent->getDownTime(), uint32_t(pointerCount),
3580 pointerProperties, samplePointerCoords,
3581 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 injectedEntries.push(injectedEntry);
3583 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3584 sampleEventTimes += 1;
3585 samplePointerCoords += pointerCount;
3586 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003587 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003588 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 motionEvent->getDisplayId(), policyFlags, action,
3590 actionButton, motionEvent->getFlags(),
3591 motionEvent->getMetaState(), motionEvent->getButtonState(),
3592 motionEvent->getClassification(),
3593 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3594 motionEvent->getYPrecision(),
3595 motionEvent->getRawXCursorPosition(),
3596 motionEvent->getRawYCursorPosition(),
3597 motionEvent->getDownTime(), uint32_t(pointerCount),
3598 pointerProperties, samplePointerCoords,
3599 motionEvent->getXOffset(), motionEvent->getYOffset());
3600 injectedEntries.push(nextInjectedEntry);
3601 }
3602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003606 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
3610 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3611 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3612 injectionState->injectionIsAsync = true;
3613 }
3614
3615 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003616 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617
3618 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003619 while (!injectedEntries.empty()) {
3620 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3621 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
3624 mLock.unlock();
3625
3626 if (needWake) {
3627 mLooper->wake();
3628 }
3629
3630 int32_t injectionResult;
3631 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003632 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633
3634 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3635 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3636 } else {
3637 for (;;) {
3638 injectionResult = injectionState->injectionResult;
3639 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3640 break;
3641 }
3642
3643 nsecs_t remainingTimeout = endTime - now();
3644 if (remainingTimeout <= 0) {
3645#if DEBUG_INJECTION
3646 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648#endif
3649 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3650 break;
3651 }
3652
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003653 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
3655
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003656 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3657 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 while (injectionState->pendingForegroundDispatches != 0) {
3659#if DEBUG_INJECTION
3660 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662#endif
3663 nsecs_t remainingTimeout = endTime - now();
3664 if (remainingTimeout <= 0) {
3665#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3667 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668#endif
3669 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3670 break;
3671 }
3672
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003673 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675 }
3676 }
3677
3678 injectionState->release();
3679 } // release lock
3680
3681#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003682 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003683 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684#endif
3685
3686 return injectionResult;
3687}
3688
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003689std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003690 std::array<uint8_t, 32> calculatedHmac;
3691 std::unique_ptr<VerifiedInputEvent> result;
3692 switch (event.getType()) {
3693 case AINPUT_EVENT_TYPE_KEY: {
3694 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3695 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3696 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003697 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003698 break;
3699 }
3700 case AINPUT_EVENT_TYPE_MOTION: {
3701 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3702 VerifiedMotionEvent verifiedMotionEvent =
3703 verifiedMotionEventFromMotionEvent(motionEvent);
3704 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003705 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003706 break;
3707 }
3708 default: {
3709 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3710 return nullptr;
3711 }
3712 }
3713 if (calculatedHmac == INVALID_HMAC) {
3714 return nullptr;
3715 }
3716 if (calculatedHmac != event.getHmac()) {
3717 return nullptr;
3718 }
3719 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003720}
3721
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 return injectorUid == 0 ||
3724 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725}
3726
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003727void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 InjectionState* injectionState = entry->injectionState;
3729 if (injectionState) {
3730#if DEBUG_INJECTION
3731 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 "injectorPid=%d, injectorUid=%d",
3733 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734#endif
3735
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 // Log the outcome since the injector did not wait for the injection result.
3738 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 case INPUT_EVENT_INJECTION_SUCCEEDED:
3740 ALOGV("Asynchronous input event injection succeeded.");
3741 break;
3742 case INPUT_EVENT_INJECTION_FAILED:
3743 ALOGW("Asynchronous input event injection failed.");
3744 break;
3745 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3746 ALOGW("Asynchronous input event injection permission denied.");
3747 break;
3748 case INPUT_EVENT_INJECTION_TIMED_OUT:
3749 ALOGW("Asynchronous input event injection timed out.");
3750 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
3752 }
3753
3754 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003755 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757}
3758
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003759void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 InjectionState* injectionState = entry->injectionState;
3761 if (injectionState) {
3762 injectionState->pendingForegroundDispatches += 1;
3763 }
3764}
3765
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003766void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 InjectionState* injectionState = entry->injectionState;
3768 if (injectionState) {
3769 injectionState->pendingForegroundDispatches -= 1;
3770
3771 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003772 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
3774 }
3775}
3776
Vishnu Nairad321cd2020-08-20 16:40:21 -07003777const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003778 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003779 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3780 auto it = mWindowHandlesByDisplay.find(displayId);
3781 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003782}
3783
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003785 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003786 if (windowHandleToken == nullptr) {
3787 return nullptr;
3788 }
3789
Arthur Hungb92218b2018-08-14 12:00:21 +08003790 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003791 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003792 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003793 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003794 return windowHandle;
3795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003798 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799}
3800
Vishnu Nairad321cd2020-08-20 16:40:21 -07003801sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3802 int displayId) const {
3803 if (windowHandleToken == nullptr) {
3804 return nullptr;
3805 }
3806
3807 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3808 if (windowHandle->getToken() == windowHandleToken) {
3809 return windowHandle;
3810 }
3811 }
3812 return nullptr;
3813}
3814
3815sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3816 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3817 return getWindowHandleLocked(focusedToken, displayId);
3818}
3819
Mady Mellor017bcd12020-06-23 19:12:00 +00003820bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3821 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003822 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003823 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003824 if (handle->getId() == windowHandle->getId() &&
3825 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003826 if (windowHandle->getInfo()->displayId != it.first) {
3827 ALOGE("Found window %s in display %" PRId32
3828 ", but it should belong to display %" PRId32,
3829 windowHandle->getName().c_str(), it.first,
3830 windowHandle->getInfo()->displayId);
3831 }
3832 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 }
3836 return false;
3837}
3838
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003839bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3840 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3841 const bool noInputChannel =
3842 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3843 if (connection != nullptr && noInputChannel) {
3844 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3845 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3846 return false;
3847 }
3848
3849 if (connection == nullptr) {
3850 if (!noInputChannel) {
3851 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3852 }
3853 return false;
3854 }
3855 if (!connection->responsive) {
3856 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3857 return false;
3858 }
3859 return true;
3860}
3861
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003862std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3863 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003864 size_t count = mInputChannelsByToken.count(token);
3865 if (count == 0) {
3866 return nullptr;
3867 }
3868 return mInputChannelsByToken.at(token);
3869}
3870
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003871void InputDispatcher::updateWindowHandlesForDisplayLocked(
3872 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3873 if (inputWindowHandles.empty()) {
3874 // Remove all handles on a display if there are no windows left.
3875 mWindowHandlesByDisplay.erase(displayId);
3876 return;
3877 }
3878
3879 // Since we compare the pointer of input window handles across window updates, we need
3880 // to make sure the handle object for the same window stays unchanged across updates.
3881 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003882 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003883 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003884 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003885 }
3886
3887 std::vector<sp<InputWindowHandle>> newHandles;
3888 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3889 if (!handle->updateInfo()) {
3890 // handle no longer valid
3891 continue;
3892 }
3893
3894 const InputWindowInfo* info = handle->getInfo();
3895 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3896 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3897 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003898 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3899 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3900 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003901 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003902 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003903 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003904 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003905 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003906 }
3907
3908 if (info->displayId != displayId) {
3909 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3910 handle->getName().c_str(), displayId, info->displayId);
3911 continue;
3912 }
3913
Robert Carredd13602020-04-13 17:24:34 -07003914 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3915 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003916 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003917 oldHandle->updateFrom(handle);
3918 newHandles.push_back(oldHandle);
3919 } else {
3920 newHandles.push_back(handle);
3921 }
3922 }
3923
3924 // Insert or replace
3925 mWindowHandlesByDisplay[displayId] = newHandles;
3926}
3927
Arthur Hung72d8dc32020-03-28 00:48:39 +00003928void InputDispatcher::setInputWindows(
3929 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3930 { // acquire lock
3931 std::scoped_lock _l(mLock);
3932 for (auto const& i : handlesPerDisplay) {
3933 setInputWindowsLocked(i.second, i.first);
3934 }
3935 }
3936 // Wake up poll loop since it may need to make new input dispatching choices.
3937 mLooper->wake();
3938}
3939
Arthur Hungb92218b2018-08-14 12:00:21 +08003940/**
3941 * Called from InputManagerService, update window handle list by displayId that can receive input.
3942 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3943 * If set an empty list, remove all handles from the specific display.
3944 * For focused handle, check if need to change and send a cancel event to previous one.
3945 * For removed handle, check if need to send a cancel event if already in touch.
3946 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003947void InputDispatcher::setInputWindowsLocked(
3948 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003949 if (DEBUG_FOCUS) {
3950 std::string windowList;
3951 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3952 windowList += iwh->getName() + " ";
3953 }
3954 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003957 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3958 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3959 const bool noInputWindow =
3960 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3961 if (noInputWindow && window->getToken() != nullptr) {
3962 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3963 window->getName().c_str());
3964 window->releaseChannel();
3965 }
3966 }
3967
Arthur Hung72d8dc32020-03-28 00:48:39 +00003968 // Copy old handles for release if they are no longer present.
3969 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Arthur Hung72d8dc32020-03-28 00:48:39 +00003971 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003972
Vishnu Nair958da932020-08-21 17:12:37 -07003973 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3974 if (mLastHoverWindowHandle &&
3975 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3976 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003977 mLastHoverWindowHandle = nullptr;
3978 }
3979
Vishnu Nair958da932020-08-21 17:12:37 -07003980 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3981 if (focusedToken) {
3982 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3983 if (result != FocusResult::OK) {
3984 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3985 }
3986 }
3987
3988 std::optional<FocusRequest> focusRequest =
3989 getOptionalValueByKey(mPendingFocusRequests, displayId);
3990 if (focusRequest) {
3991 // If the window from the pending request is now visible, provide it focus.
3992 FocusResult result = handleFocusRequestLocked(*focusRequest);
3993 if (result != FocusResult::NOT_VISIBLE) {
3994 // Drop the request if we were able to change the focus or we cannot change
3995 // it for another reason.
3996 mPendingFocusRequests.erase(displayId);
3997 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004000 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4001 mTouchStatesByDisplay.find(displayId);
4002 if (stateIt != mTouchStatesByDisplay.end()) {
4003 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004004 for (size_t i = 0; i < state.windows.size();) {
4005 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004006 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004007 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004008 ALOGD("Touched window was removed: %s in display %" PRId32,
4009 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004010 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004011 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004012 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4013 if (touchedInputChannel != nullptr) {
4014 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4015 "touched window was removed");
4016 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004018 state.windows.erase(state.windows.begin() + i);
4019 } else {
4020 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
4022 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004023 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004024
Arthur Hung72d8dc32020-03-28 00:48:39 +00004025 // Release information for windows that are no longer present.
4026 // This ensures that unused input channels are released promptly.
4027 // Otherwise, they might stick around until the window handle is destroyed
4028 // which might not happen until the next GC.
4029 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004030 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004031 if (DEBUG_FOCUS) {
4032 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004033 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004034 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004035 }
chaviw291d88a2019-02-14 10:33:58 -08004036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
4039void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004040 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004041 if (DEBUG_FOCUS) {
4042 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4043 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4044 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004045 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004046 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Chris Yea209fde2020-07-22 13:54:51 -07004048 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004049 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004050
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004051 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4052 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004053 }
4054
Chris Yea209fde2020-07-22 13:54:51 -07004055 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004056 if (inputApplicationHandle != nullptr) {
4057 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4058 } else {
4059 mFocusedApplicationHandlesByDisplay.erase(displayId);
4060 }
4061
4062 // No matter what the old focused application was, stop waiting on it because it is
4063 // no longer focused.
4064 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 } // release lock
4066
4067 // Wake up poll loop since it may need to make new input dispatching choices.
4068 mLooper->wake();
4069}
4070
Tiger Huang721e26f2018-07-24 22:26:19 +08004071/**
4072 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4073 * the display not specified.
4074 *
4075 * We track any unreleased events for each window. If a window loses the ability to receive the
4076 * released event, we will send a cancel event to it. So when the focused display is changed, we
4077 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4078 * display. The display-specified events won't be affected.
4079 */
4080void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004081 if (DEBUG_FOCUS) {
4082 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4083 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004084 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004085 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004086
4087 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004088 sp<IBinder> oldFocusedWindowToken =
4089 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4090 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004091 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004092 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004093 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 CancelationOptions
4095 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4096 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004097 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004098 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4099 }
4100 }
4101 mFocusedDisplayId = displayId;
4102
Chris Ye3c2d6f52020-08-09 10:39:48 -07004103 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004104 sp<IBinder> newFocusedWindowToken =
4105 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4106 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004107
Vishnu Nairad321cd2020-08-20 16:40:21 -07004108 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004109 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004110 if (!mFocusedWindowTokenByDisplay.empty()) {
4111 ALOGE("But another display has a focused window\n%s",
4112 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004113 }
4114 }
4115 }
4116
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004117 if (DEBUG_FOCUS) {
4118 logDispatchStateLocked();
4119 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004120 } // release lock
4121
4122 // Wake up poll loop since it may need to make new input dispatching choices.
4123 mLooper->wake();
4124}
4125
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004127 if (DEBUG_FOCUS) {
4128 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
4131 bool changed;
4132 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004133 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
4135 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4136 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004137 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 }
4139
4140 if (mDispatchEnabled && !enabled) {
4141 resetAndDropEverythingLocked("dispatcher is being disabled");
4142 }
4143
4144 mDispatchEnabled = enabled;
4145 mDispatchFrozen = frozen;
4146 changed = true;
4147 } else {
4148 changed = false;
4149 }
4150
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004151 if (DEBUG_FOCUS) {
4152 logDispatchStateLocked();
4153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 } // release lock
4155
4156 if (changed) {
4157 // Wake up poll loop since it may need to make new input dispatching choices.
4158 mLooper->wake();
4159 }
4160}
4161
4162void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004163 if (DEBUG_FOCUS) {
4164 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
4167 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004168 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
4170 if (mInputFilterEnabled == enabled) {
4171 return;
4172 }
4173
4174 mInputFilterEnabled = enabled;
4175 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4176 } // release lock
4177
4178 // Wake up poll loop since there might be work to do to drop everything.
4179 mLooper->wake();
4180}
4181
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004182void InputDispatcher::setInTouchMode(bool inTouchMode) {
4183 std::scoped_lock lock(mLock);
4184 mInTouchMode = inTouchMode;
4185}
4186
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004187void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4188 if (opacity < 0 || opacity > 1) {
4189 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4190 return;
4191 }
4192
4193 std::scoped_lock lock(mLock);
4194 mMaximumObscuringOpacityForTouch = opacity;
4195}
4196
4197void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4198 std::scoped_lock lock(mLock);
4199 mBlockUntrustedTouchesMode = mode;
4200}
4201
chaviwfbe5d9c2018-12-26 12:23:37 -08004202bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4203 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004204 if (DEBUG_FOCUS) {
4205 ALOGD("Trivial transfer to same window.");
4206 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004207 return true;
4208 }
4209
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004211 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212
chaviwfbe5d9c2018-12-26 12:23:37 -08004213 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4214 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004215 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004216 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 return false;
4218 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004219 if (DEBUG_FOCUS) {
4220 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4221 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004224 if (DEBUG_FOCUS) {
4225 ALOGD("Cannot transfer focus because windows are on different displays.");
4226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 return false;
4228 }
4229
4230 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004231 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4232 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004233 for (size_t i = 0; i < state.windows.size(); i++) {
4234 const TouchedWindow& touchedWindow = state.windows[i];
4235 if (touchedWindow.windowHandle == fromWindowHandle) {
4236 int32_t oldTargetFlags = touchedWindow.targetFlags;
4237 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004239 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 int32_t newTargetFlags = oldTargetFlags &
4242 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4243 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004244 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245
Jeff Brownf086ddb2014-02-11 14:28:48 -08004246 found = true;
4247 goto Found;
4248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004253 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004254 if (DEBUG_FOCUS) {
4255 ALOGD("Focus transfer failed because from window did not have focus.");
4256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 return false;
4258 }
4259
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004260 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4261 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004262 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004263 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 CancelationOptions
4265 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4266 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004268 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004271 if (DEBUG_FOCUS) {
4272 logDispatchStateLocked();
4273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 } // release lock
4275
4276 // Wake up poll loop since it may need to make new input dispatching choices.
4277 mLooper->wake();
4278 return true;
4279}
4280
4281void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004282 if (DEBUG_FOCUS) {
4283 ALOGD("Resetting and dropping all events (%s).", reason);
4284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
4286 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4287 synthesizeCancelationEventsForAllConnectionsLocked(options);
4288
4289 resetKeyRepeatLocked();
4290 releasePendingEventLocked();
4291 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004292 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004294 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004295 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004297 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298}
4299
4300void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004301 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 dumpDispatchStateLocked(dump);
4303
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004304 std::istringstream stream(dump);
4305 std::string line;
4306
4307 while (std::getline(stream, line, '\n')) {
4308 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 }
4310}
4311
Vishnu Nairad321cd2020-08-20 16:40:21 -07004312std::string InputDispatcher::dumpFocusedWindowsLocked() {
4313 if (mFocusedWindowTokenByDisplay.empty()) {
4314 return INDENT "FocusedWindows: <none>\n";
4315 }
4316
4317 std::string dump;
4318 dump += INDENT "FocusedWindows:\n";
4319 for (auto& it : mFocusedWindowTokenByDisplay) {
4320 const int32_t displayId = it.first;
4321 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4322 if (windowHandle) {
4323 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4324 windowHandle->getName().c_str());
4325 } else {
4326 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4327 " has focused token without a window'\n",
4328 displayId);
4329 }
4330 }
4331 return dump;
4332}
4333
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004335 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4336 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4337 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004338 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Tiger Huang721e26f2018-07-24 22:26:19 +08004340 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4341 dump += StringPrintf(INDENT "FocusedApplications:\n");
4342 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4343 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004344 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004345 const std::chrono::duration timeout =
4346 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004347 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004348 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004349 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004352 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004354
Vishnu Nairad321cd2020-08-20 16:40:21 -07004355 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004357 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004358 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004359 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4360 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004361 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 state.displayId, toString(state.down), toString(state.split),
4363 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004364 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004365 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004366 for (size_t i = 0; i < state.windows.size(); i++) {
4367 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 dump += StringPrintf(INDENT4
4369 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4370 i, touchedWindow.windowHandle->getName().c_str(),
4371 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004372 }
4373 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004375 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004376 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004377 dump += INDENT3 "Portal windows:\n";
4378 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004379 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4381 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004382 }
4383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004386 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
4388
Arthur Hungb92218b2018-08-14 12:00:21 +08004389 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004391 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004392 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004393 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004394 dump += INDENT2 "Windows:\n";
4395 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004396 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004397 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
Arthur Hungb92218b2018-08-14 12:00:21 +08004399 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004400 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4401 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004402 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004404 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004405 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004406 i, windowInfo->name.c_str(), windowInfo->displayId,
4407 windowInfo->portalToDisplayId,
4408 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004409 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 toString(windowInfo->hasWallpaper),
4411 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004412 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004413 static_cast<int32_t>(windowInfo->type),
4414 windowInfo->frameLeft, windowInfo->frameTop,
4415 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004416 windowInfo->globalScaleFactor,
4417 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004418 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004419 dump += StringPrintf(", inputFeatures=%s",
4420 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4422 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004424 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004425 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004426 }
4427 } else {
4428 dump += INDENT2 "Windows: <none>\n";
4429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
4431 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004432 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 }
4434
Michael Wright3dd60e22019-03-27 22:06:44 +00004435 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 const std::vector<Monitor>& monitors = it.second;
4438 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4439 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 }
4441 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004442 const std::vector<Monitor>& monitors = it.second;
4443 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4444 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004447 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 }
4449
4450 nsecs_t currentTime = now();
4451
4452 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004453 if (!mRecentQueue.empty()) {
4454 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4455 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004456 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004458 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004461 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 }
4463
4464 // Dump event currently being dispatched.
4465 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004466 dump += INDENT "PendingEvent:\n";
4467 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004469 dump += StringPrintf(", age=%" PRId64 "ms\n",
4470 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004472 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473 }
4474
4475 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004476 if (!mInboundQueue.empty()) {
4477 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4478 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004479 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004481 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004484 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 }
4486
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004487 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004488 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004489 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4490 const KeyReplacement& replacement = pair.first;
4491 int32_t newKeyCode = pair.second;
4492 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004493 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004494 }
4495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004496 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004497 }
4498
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004499 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004500 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004501 for (const auto& pair : mConnectionsByFd) {
4502 const sp<Connection>& connection = pair.second;
4503 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004504 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004505 pair.first, connection->getInputChannelName().c_str(),
4506 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004507 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004509 if (!connection->outboundQueue.empty()) {
4510 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4511 connection->outboundQueue.size());
4512 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 dump.append(INDENT4);
4514 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004515 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4516 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004517 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004518 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
4520 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004521 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 }
4523
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004524 if (!connection->waitQueue.empty()) {
4525 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4526 connection->waitQueue.size());
4527 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004528 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004530 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004531 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004533 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004534 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004537 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 }
4539 }
4540 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004541 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 }
4543
4544 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004545 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4546 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004548 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
4550
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004551 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004552 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4553 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4554 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555}
4556
Michael Wright3dd60e22019-03-27 22:06:44 +00004557void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4558 const size_t numMonitors = monitors.size();
4559 for (size_t i = 0; i < numMonitors; i++) {
4560 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004561 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004562 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4563 dump += "\n";
4564 }
4565}
4566
Garfield Tan15601662020-09-22 15:32:38 -07004567base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4568 const std::string& name) {
4569#if DEBUG_CHANNEL_CREATION
4570 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571#endif
4572
Garfield Tan15601662020-09-22 15:32:38 -07004573 std::shared_ptr<InputChannel> serverChannel;
4574 std::unique_ptr<InputChannel> clientChannel;
4575 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4576
4577 if (result) {
4578 return base::Error(result) << "Failed to open input channel pair with name " << name;
4579 }
4580
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004582 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004583 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584
Garfield Tan15601662020-09-22 15:32:38 -07004585 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004586 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004587 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4590 } // release lock
4591
4592 // Wake the looper because some connections have changed.
4593 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004594 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595}
4596
Garfield Tan15601662020-09-22 15:32:38 -07004597base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4598 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4599 std::shared_ptr<InputChannel> serverChannel;
4600 std::unique_ptr<InputChannel> clientChannel;
4601 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4602 if (result) {
4603 return base::Error(result) << "Failed to open input channel pair with name " << name;
4604 }
4605
Michael Wright3dd60e22019-03-27 22:06:44 +00004606 { // acquire lock
4607 std::scoped_lock _l(mLock);
4608
4609 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004610 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4611 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004612 }
4613
Garfield Tan15601662020-09-22 15:32:38 -07004614 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004615
Garfield Tan15601662020-09-22 15:32:38 -07004616 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004617 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004618 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004619
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004620 auto& monitorsByDisplay =
4621 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004622 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004623
4624 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004625 }
Garfield Tan15601662020-09-22 15:32:38 -07004626
Michael Wright3dd60e22019-03-27 22:06:44 +00004627 // Wake the looper because some connections have changed.
4628 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004629 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004630}
4631
Garfield Tan15601662020-09-22 15:32:38 -07004632status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004634 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635
Garfield Tan15601662020-09-22 15:32:38 -07004636 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 if (status) {
4638 return status;
4639 }
4640 } // release lock
4641
4642 // Wake the poll loop because removing the connection may have changed the current
4643 // synchronization state.
4644 mLooper->wake();
4645 return OK;
4646}
4647
Garfield Tan15601662020-09-22 15:32:38 -07004648status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4649 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004650 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004651 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004652 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 return BAD_VALUE;
4654 }
4655
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004656 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004657 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004658
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004660 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 }
4662
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004663 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664
4665 nsecs_t currentTime = now();
4666 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4667
4668 connection->status = Connection::STATUS_ZOMBIE;
4669 return OK;
4670}
4671
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004672void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4673 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4674 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004675}
4676
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004677void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004678 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004679 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004681 std::vector<Monitor>& monitors = it->second;
4682 const size_t numMonitors = monitors.size();
4683 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004684 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 monitors.erase(monitors.begin() + i);
4686 break;
4687 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004688 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004689 if (monitors.empty()) {
4690 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004691 } else {
4692 ++it;
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 }
4695}
4696
Michael Wright3dd60e22019-03-27 22:06:44 +00004697status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4698 { // acquire lock
4699 std::scoped_lock _l(mLock);
4700 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4701
4702 if (!foundDisplayId) {
4703 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4704 return BAD_VALUE;
4705 }
4706 int32_t displayId = foundDisplayId.value();
4707
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004708 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4709 mTouchStatesByDisplay.find(displayId);
4710 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004711 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4712 return BAD_VALUE;
4713 }
4714
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004715 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004716 std::optional<int32_t> foundDeviceId;
4717 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004718 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004719 foundDeviceId = state.deviceId;
4720 }
4721 }
4722 if (!foundDeviceId || !state.down) {
4723 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004724 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004725 return BAD_VALUE;
4726 }
4727 int32_t deviceId = foundDeviceId.value();
4728
4729 // Send cancel events to all the input channels we're stealing from.
4730 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004731 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004732 options.deviceId = deviceId;
4733 options.displayId = displayId;
4734 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004735 std::shared_ptr<InputChannel> channel =
4736 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004737 if (channel != nullptr) {
4738 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4739 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004740 }
4741 // Then clear the current touch state so we stop dispatching to them as well.
4742 state.filterNonMonitors();
4743 }
4744 return OK;
4745}
4746
Michael Wright3dd60e22019-03-27 22:06:44 +00004747std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4748 const sp<IBinder>& token) {
4749 for (const auto& it : mGestureMonitorsByDisplay) {
4750 const std::vector<Monitor>& monitors = it.second;
4751 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004752 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004753 return it.first;
4754 }
4755 }
4756 }
4757 return std::nullopt;
4758}
4759
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004760sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004761 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004762 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004763 }
4764
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004765 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004766 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004767 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004768 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
4770 }
Robert Carr4e670e52018-08-15 13:26:12 -07004771
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004772 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773}
4774
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004775void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004777 removeByValue(mConnectionsByFd, connection);
4778}
4779
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004780void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4781 const sp<Connection>& connection, uint32_t seq,
4782 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004783 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4784 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 commandEntry->connection = connection;
4786 commandEntry->eventTime = currentTime;
4787 commandEntry->seq = seq;
4788 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004789 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790}
4791
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4793 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004797 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4798 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004800 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801}
4802
Vishnu Nairad321cd2020-08-20 16:40:21 -07004803void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4804 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004805 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4806 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004807 commandEntry->oldToken = oldToken;
4808 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004809 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004810}
4811
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004812void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4814 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004815 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004816 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004817 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818 return;
4819 }
4820 /**
4821 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4822 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4823 * has changed. This could cause newer entries to time out before the already dispatched
4824 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4825 * processes the events linearly. So providing information about the oldest entry seems to be
4826 * most useful.
4827 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004828 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4830 std::string reason =
4831 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004832 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833 ns2ms(currentWait),
4834 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004836 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 reason);
4838
4839 std::unique_ptr<CommandEntry> commandEntry =
4840 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4841 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004842 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843 commandEntry->reason = std::move(reason);
4844 postCommandLocked(std::move(commandEntry));
4845}
4846
Chris Yea209fde2020-07-22 13:54:51 -07004847void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4849 application->getName().c_str());
4850
4851 updateLastAnrStateLocked(application, reason);
4852
4853 std::unique_ptr<CommandEntry> commandEntry =
4854 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4855 commandEntry->inputApplicationHandle = application;
4856 commandEntry->inputChannel = nullptr;
4857 commandEntry->reason = std::move(reason);
4858 postCommandLocked(std::move(commandEntry));
4859}
4860
4861void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4862 const std::string& reason) {
4863 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4864 updateLastAnrStateLocked(windowLabel, reason);
4865}
4866
Chris Yea209fde2020-07-22 13:54:51 -07004867void InputDispatcher::updateLastAnrStateLocked(
4868 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004869 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4870 updateLastAnrStateLocked(windowLabel, reason);
4871}
4872
4873void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4874 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004876 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 struct tm tm;
4878 localtime_r(&t, &tm);
4879 char timestr[64];
4880 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004881 mLastAnrState.clear();
4882 mLastAnrState += INDENT "ANR:\n";
4883 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4885 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004886 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887}
4888
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004889void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 mLock.unlock();
4891
4892 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4893
4894 mLock.lock();
4895}
4896
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004897void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 sp<Connection> connection = commandEntry->connection;
4899
4900 if (connection->status != Connection::STATUS_ZOMBIE) {
4901 mLock.unlock();
4902
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004903 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904
4905 mLock.lock();
4906 }
4907}
4908
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004909void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004910 sp<IBinder> oldToken = commandEntry->oldToken;
4911 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004912 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004913 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004914 mLock.lock();
4915}
4916
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004917void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004918 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004919 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 mLock.unlock();
4921
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004922 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004923 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924
4925 mLock.lock();
4926
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004927 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004928 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4929 } else {
4930 // stop waking up for events in this connection, it is already not responding
4931 sp<Connection> connection = getConnectionLocked(token);
4932 if (connection == nullptr) {
4933 return;
4934 }
4935 cancelEventsForAnrLocked(connection);
4936 }
4937}
4938
Chris Yea209fde2020-07-22 13:54:51 -07004939void InputDispatcher::extendAnrTimeoutsLocked(
4940 const std::shared_ptr<InputApplicationHandle>& application,
4941 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004942 if (connectionToken == nullptr && application != nullptr) {
4943 // The ANR happened because there's no focused window
4944 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4945 mAwaitedFocusedApplication = application;
4946 }
4947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948 sp<Connection> connection = getConnectionLocked(connectionToken);
4949 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004950 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951 return;
4952 }
4953
4954 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004955 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956
4957 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004958 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959 for (DispatchEntry* entry : connection->waitQueue) {
4960 if (newTimeout >= entry->timeoutTime) {
4961 // Already removed old entries when connection was marked unresponsive
4962 entry->timeoutTime = newTimeout;
4963 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4964 }
4965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966}
4967
4968void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4969 CommandEntry* commandEntry) {
4970 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004971 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
4973 mLock.unlock();
4974
Michael Wright2b3c3302018-03-02 17:19:13 +00004975 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004976 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004977 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 : nullptr;
4979 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004980 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4981 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004982 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984
4985 mLock.lock();
4986
4987 if (delay < 0) {
4988 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4989 } else if (!delay) {
4990 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4991 } else {
4992 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4993 entry->interceptKeyWakeupTime = now() + delay;
4994 }
4995 entry->release();
4996}
4997
chaviwfd6d3512019-03-25 13:23:49 -07004998void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4999 mLock.unlock();
5000 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5001 mLock.lock();
5002}
5003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004/**
5005 * Connection is responsive if it has no events in the waitQueue that are older than the
5006 * current time.
5007 */
5008static bool isConnectionResponsive(const Connection& connection) {
5009 const nsecs_t currentTime = now();
5010 for (const DispatchEntry* entry : connection.waitQueue) {
5011 if (entry->timeoutTime < currentTime) {
5012 return false;
5013 }
5014 }
5015 return true;
5016}
5017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005018void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005020 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005022 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023
5024 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005025 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005026 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005027 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005029 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005030 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005031 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005032 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5033 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005034 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005035 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005036
5037 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005038 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005039 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5040 restartEvent =
5041 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005042 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005043 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5044 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5045 handled);
5046 } else {
5047 restartEvent = false;
5048 }
5049
5050 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005051 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005052 // contents of the wait queue to have been drained, so we need to double-check
5053 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005054 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5055 if (dispatchEntryIt != connection->waitQueue.end()) {
5056 dispatchEntry = *dispatchEntryIt;
5057 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005058 mAnrTracker.erase(dispatchEntry->timeoutTime,
5059 connection->inputChannel->getConnectionToken());
5060 if (!connection->responsive) {
5061 connection->responsive = isConnectionResponsive(*connection);
5062 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005063 traceWaitQueueLength(connection);
5064 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005065 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005066 traceOutboundQueueLength(connection);
5067 } else {
5068 releaseDispatchEntry(dispatchEntry);
5069 }
5070 }
5071
5072 // Start the next dispatch cycle for this connection.
5073 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074}
5075
5076bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005077 DispatchEntry* dispatchEntry,
5078 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005079 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005080 if (!handled) {
5081 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005082 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005083 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005084 return false;
5085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005087 // Get the fallback key state.
5088 // Clear it out after dispatching the UP.
5089 int32_t originalKeyCode = keyEntry->keyCode;
5090 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5091 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5092 connection->inputState.removeFallbackKey(originalKeyCode);
5093 }
5094
5095 if (handled || !dispatchEntry->hasForegroundTarget()) {
5096 // If the application handles the original key for which we previously
5097 // generated a fallback or if the window is not a foreground window,
5098 // then cancel the associated fallback key, if any.
5099 if (fallbackKeyCode != -1) {
5100 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005102 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005103 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5104 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5105 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005107 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005108 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109
5110 mLock.unlock();
5111
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005112 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005113 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114
5115 mLock.lock();
5116
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005117 // Cancel the fallback key.
5118 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005120 "application handled the original non-fallback key "
5121 "or is no longer a foreground target, "
5122 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 options.keyCode = fallbackKeyCode;
5124 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005126 connection->inputState.removeFallbackKey(originalKeyCode);
5127 }
5128 } else {
5129 // If the application did not handle a non-fallback key, first check
5130 // that we are in a good state to perform unhandled key event processing
5131 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005132 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005133 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005135 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005136 "since this is not an initial down. "
5137 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5138 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005140 return false;
5141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005143 // Dispatch the unhandled key to the policy.
5144#if DEBUG_OUTBOUND_EVENT_DETAILS
5145 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005146 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5147 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005148#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005149 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005150
5151 mLock.unlock();
5152
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005153 bool fallback =
5154 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5155 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005156
5157 mLock.lock();
5158
5159 if (connection->status != Connection::STATUS_NORMAL) {
5160 connection->inputState.removeFallbackKey(originalKeyCode);
5161 return false;
5162 }
5163
5164 // Latch the fallback keycode for this key on an initial down.
5165 // The fallback keycode cannot change at any other point in the lifecycle.
5166 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005168 fallbackKeyCode = event.getKeyCode();
5169 } else {
5170 fallbackKeyCode = AKEYCODE_UNKNOWN;
5171 }
5172 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5173 }
5174
5175 ALOG_ASSERT(fallbackKeyCode != -1);
5176
5177 // Cancel the fallback key if the policy decides not to send it anymore.
5178 // We will continue to dispatch the key to the policy but we will no
5179 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005180 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5181 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005182#if DEBUG_OUTBOUND_EVENT_DETAILS
5183 if (fallback) {
5184 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005185 "as a fallback for %d, but on the DOWN it had requested "
5186 "to send %d instead. Fallback canceled.",
5187 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005188 } else {
5189 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005190 "but on the DOWN it had requested to send %d. "
5191 "Fallback canceled.",
5192 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005193 }
5194#endif
5195
5196 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5197 "canceling fallback, policy no longer desires it");
5198 options.keyCode = fallbackKeyCode;
5199 synthesizeCancelationEventsForConnectionLocked(connection, options);
5200
5201 fallback = false;
5202 fallbackKeyCode = AKEYCODE_UNKNOWN;
5203 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005205 }
5206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207
5208#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005209 {
5210 std::string msg;
5211 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5212 connection->inputState.getFallbackKeys();
5213 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005214 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005216 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005217 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005218 }
5219#endif
5220
5221 if (fallback) {
5222 // Restart the dispatch cycle using the fallback key.
5223 keyEntry->eventTime = event.getEventTime();
5224 keyEntry->deviceId = event.getDeviceId();
5225 keyEntry->source = event.getSource();
5226 keyEntry->displayId = event.getDisplayId();
5227 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5228 keyEntry->keyCode = fallbackKeyCode;
5229 keyEntry->scanCode = event.getScanCode();
5230 keyEntry->metaState = event.getMetaState();
5231 keyEntry->repeatCount = event.getRepeatCount();
5232 keyEntry->downTime = event.getDownTime();
5233 keyEntry->syntheticRepeat = false;
5234
5235#if DEBUG_OUTBOUND_EVENT_DETAILS
5236 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005237 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5238 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005239#endif
5240 return true; // restart the event
5241 } else {
5242#if DEBUG_OUTBOUND_EVENT_DETAILS
5243 ALOGD("Unhandled key event: No fallback key.");
5244#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005245
5246 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005247 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 }
5249 }
5250 return false;
5251}
5252
5253bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005254 DispatchEntry* dispatchEntry,
5255 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 return false;
5257}
5258
5259void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5260 mLock.unlock();
5261
5262 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5263
5264 mLock.lock();
5265}
5266
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005267KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5268 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005269 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005270 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5271 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005272 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273}
5274
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005275void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5276 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 // TODO Write some statistics about how long we spend waiting.
5278}
5279
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005280/**
5281 * Report the touch event latency to the statsd server.
5282 * Input events are reported for statistics if:
5283 * - This is a touchscreen event
5284 * - InputFilter is not enabled
5285 * - Event is not injected or synthesized
5286 *
5287 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5288 * from getting aggregated with the "old" data.
5289 */
5290void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5291 REQUIRES(mLock) {
5292 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5293 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5294 if (!reportForStatistics) {
5295 return;
5296 }
5297
5298 if (mTouchStatistics.shouldReport()) {
5299 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5300 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5301 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5302 mTouchStatistics.reset();
5303 }
5304 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5305 mTouchStatistics.addValue(latencyMicros);
5306}
5307
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308void InputDispatcher::traceInboundQueueLengthLocked() {
5309 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005310 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312}
5313
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005314void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 if (ATRACE_ENABLED()) {
5316 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005317 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005318 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
5320}
5321
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005322void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 if (ATRACE_ENABLED()) {
5324 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005325 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005326 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328}
5329
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005330void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005331 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005333 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 dumpDispatchStateLocked(dump);
5335
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005336 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005337 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005338 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 }
5340}
5341
5342void InputDispatcher::monitor() {
5343 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005344 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005346 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347}
5348
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005349/**
5350 * Wake up the dispatcher and wait until it processes all events and commands.
5351 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5352 * this method can be safely called from any thread, as long as you've ensured that
5353 * the work you are interested in completing has already been queued.
5354 */
5355bool InputDispatcher::waitForIdle() {
5356 /**
5357 * Timeout should represent the longest possible time that a device might spend processing
5358 * events and commands.
5359 */
5360 constexpr std::chrono::duration TIMEOUT = 100ms;
5361 std::unique_lock lock(mLock);
5362 mLooper->wake();
5363 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5364 return result == std::cv_status::no_timeout;
5365}
5366
Vishnu Naire798b472020-07-23 13:52:21 -07005367/**
5368 * Sets focus to the window identified by the token. This must be called
5369 * after updating any input window handles.
5370 *
5371 * Params:
5372 * request.token - input channel token used to identify the window that should gain focus.
5373 * request.focusedToken - the token that the caller expects currently to be focused. If the
5374 * specified token does not match the currently focused window, this request will be dropped.
5375 * If the specified focused token matches the currently focused window, the call will succeed.
5376 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5377 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5378 * when requesting the focus change. This determines which request gets
5379 * precedence if there is a focus change request from another source such as pointer down.
5380 */
Vishnu Nair958da932020-08-21 17:12:37 -07005381void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5382 { // acquire lock
5383 std::scoped_lock _l(mLock);
5384
5385 const int32_t displayId = request.displayId;
5386 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5387 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5388 ALOGD_IF(DEBUG_FOCUS,
5389 "setFocusedWindow on display %" PRId32
5390 " ignored, reason: focusedToken is not focused",
5391 displayId);
5392 return;
5393 }
5394
5395 mPendingFocusRequests.erase(displayId);
5396 FocusResult result = handleFocusRequestLocked(request);
5397 if (result == FocusResult::NOT_VISIBLE) {
5398 // The requested window is not currently visible. Wait for the window to become visible
5399 // and then provide it focus. This is to handle situations where a user action triggers
5400 // a new window to appear. We want to be able to queue any key events after the user
5401 // action and deliver it to the newly focused window. In order for this to happen, we
5402 // take focus from the currently focused window so key events can be queued.
5403 ALOGD_IF(DEBUG_FOCUS,
5404 "setFocusedWindow on display %" PRId32
5405 " pending, reason: window is not visible",
5406 displayId);
5407 mPendingFocusRequests[displayId] = request;
5408 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5409 "setFocusedWindow_AwaitingWindowVisibility");
5410 } else if (result != FocusResult::OK) {
5411 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5412 typeToString(result));
5413 }
5414 } // release lock
5415 // Wake up poll loop since it may need to make new input dispatching choices.
5416 mLooper->wake();
5417}
5418
5419InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5420 const FocusRequest& request) {
5421 const int32_t displayId = request.displayId;
5422 const sp<IBinder> newFocusedToken = request.token;
5423 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5424
5425 if (oldFocusedToken == request.token) {
5426 ALOGD_IF(DEBUG_FOCUS,
5427 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5428 displayId);
5429 return FocusResult::OK;
5430 }
5431
5432 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5433 if (result != FocusResult::OK) {
5434 return result;
5435 }
5436
5437 std::string_view reason =
5438 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5439 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5440 return FocusResult::OK;
5441}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005442
Vishnu Nairad321cd2020-08-20 16:40:21 -07005443void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5444 const sp<IBinder>& newFocusedToken, int32_t displayId,
5445 std::string_view reason) {
5446 if (oldFocusedToken) {
5447 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005448 if (focusedInputChannel) {
5449 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5450 "focus left window");
5451 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005452 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005453 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005454 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005455 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005456 if (newFocusedToken) {
5457 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5458 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005459 }
5460
5461 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005462 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005463 }
5464}
Vishnu Nair958da932020-08-21 17:12:37 -07005465
5466/**
5467 * Checks if the window token can be focused on a display. The token can be focused if there is
5468 * at least one window handle that is visible with the same token and all window handles with the
5469 * same token are focusable.
5470 *
5471 * In the case of mirroring, two windows may share the same window token and their visibility
5472 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5473 * we expect the focusability of the windows to match since its hard to reason why one window can
5474 * receive focus events and the other cannot when both are backed by the same input channel.
5475 */
5476InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5477 int32_t displayId) const {
5478 bool allWindowsAreFocusable = true;
5479 bool visibleWindowFound = false;
5480 bool windowFound = false;
5481 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5482 if (window->getToken() != token) {
5483 continue;
5484 }
5485 windowFound = true;
5486 if (window->getInfo()->visible) {
5487 // Check if at least a single window is visible.
5488 visibleWindowFound = true;
5489 }
5490 if (!window->getInfo()->focusable) {
5491 // Check if all windows with the window token are focusable.
5492 allWindowsAreFocusable = false;
5493 break;
5494 }
5495 }
5496
5497 if (!windowFound) {
5498 return FocusResult::NO_WINDOW;
5499 }
5500 if (!allWindowsAreFocusable) {
5501 return FocusResult::NOT_FOCUSABLE;
5502 }
5503 if (!visibleWindowFound) {
5504 return FocusResult::NOT_VISIBLE;
5505 }
5506
5507 return FocusResult::OK;
5508}
Garfield Tane84e6f92019-08-29 17:28:41 -07005509} // namespace android::inputdispatcher