blob: 0f06ddfcbdcd3c06adedebf774f9fa3033bb51cb [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
Vishnu Nair958da932020-08-21 17:12:37 -0700255/**
256 * Find the entry in std::unordered_map by key and return the value as an optional.
257 */
258template <typename K, typename V>
259static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
260 auto it = map.find(key);
261 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
262}
263
chaviwaf87b3e2019-10-01 16:59:28 -0700264static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
265 if (first == second) {
266 return true;
267 }
268
269 if (first == nullptr || second == nullptr) {
270 return false;
271 }
272
273 return first->getToken() == second->getToken();
274}
275
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800276static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
277 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
278}
279
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000280static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
281 EventEntry* eventEntry,
282 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700283 if (inputTarget.useDefaultPointerTransform()) {
284 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000285 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700286 inputTargetFlags, transform,
287 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000288 }
289
290 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
291 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
292
293 PointerCoords pointerCoords[motionEntry.pointerCount];
294
295 // Use the first pointer information to normalize all other pointers. This could be any pointer
296 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 // uses the transform for the normalized pointer.
298 const ui::Transform& firstPointerTransform =
299 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
300 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000301
302 // Iterate through all pointers in the event to normalize against the first.
303 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
304 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
305 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700306 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 // First, apply the current pointer's transform to update the coordinates into
310 // window space.
311 pointerCoords[pointerIndex].transform(currTransform);
312 // Next, apply the inverse transform of the normalized coordinates so the
313 // current coordinates are transformed into the normalized coordinate space.
314 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 }
316
317 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800318 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
320 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
321 motionEntry.metaState, motionEntry.buttonState,
322 motionEntry.classification, motionEntry.edgeFlags,
323 motionEntry.xPrecision, motionEntry.yPrecision,
324 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
325 motionEntry.downTime, motionEntry.pointerCount,
326 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
327 0 /* yOffset */);
328
329 if (motionEntry.injectionState) {
330 combinedMotionEntry->injectionState = motionEntry.injectionState;
331 combinedMotionEntry->injectionState->refCount += 1;
332 }
333
334 std::unique_ptr<DispatchEntry> dispatchEntry =
335 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 inputTargetFlags, firstPointerTransform,
337 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338 combinedMotionEntry->release();
339 return dispatchEntry;
340}
341
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700342static void addGestureMonitors(const std::vector<Monitor>& monitors,
343 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
344 float yOffset = 0) {
345 if (monitors.empty()) {
346 return;
347 }
348 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
349 for (const Monitor& monitor : monitors) {
350 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
351 }
352}
353
Garfield Tan15601662020-09-22 15:32:38 -0700354static status_t openInputChannelPair(const std::string& name,
355 std::shared_ptr<InputChannel>& serverChannel,
356 std::unique_ptr<InputChannel>& clientChannel) {
357 std::unique_ptr<InputChannel> uniqueServerChannel;
358 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
359
360 serverChannel = std::move(uniqueServerChannel);
361 return result;
362}
363
Vishnu Nair958da932020-08-21 17:12:37 -0700364const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
365 switch (result) {
366 case InputDispatcher::FocusResult::OK:
367 return "Ok";
368 case InputDispatcher::FocusResult::NO_WINDOW:
369 return "Window not found";
370 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
371 return "Window not focusable";
372 case InputDispatcher::FocusResult::NOT_VISIBLE:
373 return "Window not visible";
374 }
375}
376
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500377template <typename T>
378static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
379 if (lhs == nullptr && rhs == nullptr) {
380 return true;
381 }
382 if (lhs == nullptr || rhs == nullptr) {
383 return false;
384 }
385 return *lhs == *rhs;
386}
387
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388// --- InputDispatcher ---
389
Garfield Tan00f511d2019-06-12 16:55:40 -0700390InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
391 : mPolicy(policy),
392 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700393 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800394 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700395 mAppSwitchSawKeyDown(false),
396 mAppSwitchDueTime(LONG_LONG_MAX),
397 mNextUnblockedEvent(nullptr),
398 mDispatchEnabled(false),
399 mDispatchFrozen(false),
400 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800401 // mInTouchMode will be initialized by the WindowManager to the default device config.
402 // To avoid leaking stack in case that call never comes, and for tests,
403 // initialize it here anyways.
404 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700405 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800407 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800408
Yi Kong9b14ac62018-07-17 13:48:38 -0700409 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410
411 policy->getDispatcherConfiguration(&mConfig);
412}
413
414InputDispatcher::~InputDispatcher() {
415 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800416 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417
418 resetKeyRepeatLocked();
419 releasePendingEventLocked();
420 drainInboundQueueLocked();
421 }
422
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700423 while (!mConnectionsByFd.empty()) {
424 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700425 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 }
427}
428
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700429status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700430 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700431 return ALREADY_EXISTS;
432 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 mThread = std::make_unique<InputThread>(
434 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
435 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436}
437
438status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700439 if (mThread && mThread->isCallingThread()) {
440 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441 return INVALID_OPERATION;
442 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700443 mThread.reset();
444 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700445}
446
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447void InputDispatcher::dispatchOnce() {
448 nsecs_t nextWakeupTime = LONG_LONG_MAX;
449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800450 std::scoped_lock _l(mLock);
451 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
453 // Run a dispatch loop if there are no pending commands.
454 // The dispatch loop might enqueue commands to run afterwards.
455 if (!haveCommandsLocked()) {
456 dispatchOnceInnerLocked(&nextWakeupTime);
457 }
458
459 // Run all pending commands if there are any.
460 // If any commands were run then force the next poll to wake up immediately.
461 if (runCommandsLockedInterruptible()) {
462 nextWakeupTime = LONG_LONG_MIN;
463 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800464
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700465 // If we are still waiting for ack on some events,
466 // we might have to wake up earlier to check if an app is anr'ing.
467 const nsecs_t nextAnrCheck = processAnrsLocked();
468 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
469
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470 // We are about to enter an infinitely long sleep, because we have no commands or
471 // pending or queued events
472 if (nextWakeupTime == LONG_LONG_MAX) {
473 mDispatcherEnteredIdle.notify_all();
474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 } // release lock
476
477 // Wait for callback or timeout or wake. (make sure we round up, not down)
478 nsecs_t currentTime = now();
479 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
480 mLooper->pollOnce(timeoutMillis);
481}
482
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700483/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500484 * Raise ANR if there is no focused window.
485 * Before the ANR is raised, do a final state check:
486 * 1. The currently focused application must be the same one we are waiting for.
487 * 2. Ensure we still don't have a focused window.
488 */
489void InputDispatcher::processNoFocusedWindowAnrLocked() {
490 // Check if the application that we are waiting for is still focused.
491 std::shared_ptr<InputApplicationHandle> focusedApplication =
492 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
493 if (focusedApplication == nullptr ||
494 focusedApplication->getApplicationToken() !=
495 mAwaitedFocusedApplication->getApplicationToken()) {
496 // Unexpected because we should have reset the ANR timer when focused application changed
497 ALOGE("Waited for a focused window, but focused application has already changed to %s",
498 focusedApplication->getName().c_str());
499 return; // The focused application has changed.
500 }
501
502 const sp<InputWindowHandle>& focusedWindowHandle =
503 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
504 if (focusedWindowHandle != nullptr) {
505 return; // We now have a focused window. No need for ANR.
506 }
507 onAnrLocked(mAwaitedFocusedApplication);
508}
509
510/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700511 * Check if any of the connections' wait queues have events that are too old.
512 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
513 * Return the time at which we should wake up next.
514 */
515nsecs_t InputDispatcher::processAnrsLocked() {
516 const nsecs_t currentTime = now();
517 nsecs_t nextAnrCheck = LONG_LONG_MAX;
518 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
519 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
520 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500521 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700522 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500523 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700524 return LONG_LONG_MIN;
525 } else {
526 // Keep waiting
527 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
528 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
529 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
530 }
531 }
532
533 // Check if any connection ANRs are due
534 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
535 if (currentTime < nextAnrCheck) { // most likely scenario
536 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
537 }
538
539 // If we reached here, we have an unresponsive connection.
540 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
541 if (connection == nullptr) {
542 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
543 return nextAnrCheck;
544 }
545 connection->responsive = false;
546 // Stop waking up for this unresponsive connection
547 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500548 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700549 return LONG_LONG_MIN;
550}
551
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500552std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700553 sp<InputWindowHandle> window = getWindowHandleLocked(token);
554 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500555 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700556 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500557 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700558}
559
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
561 nsecs_t currentTime = now();
562
Jeff Browndc5992e2014-04-11 01:27:26 -0700563 // Reset the key repeat timer whenever normal dispatch is suspended while the
564 // device is in a non-interactive state. This is to ensure that we abort a key
565 // repeat if the device is just coming out of sleep.
566 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 resetKeyRepeatLocked();
568 }
569
570 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
571 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100572 if (DEBUG_FOCUS) {
573 ALOGD("Dispatch frozen. Waiting some more.");
574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 return;
576 }
577
578 // Optimize latency of app switches.
579 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
580 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
581 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
582 if (mAppSwitchDueTime < *nextWakeupTime) {
583 *nextWakeupTime = mAppSwitchDueTime;
584 }
585
586 // Ready to start a new event.
587 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700588 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700589 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 if (isAppSwitchDue) {
591 // The inbound queue is empty so the app switch key we were waiting
592 // for will never arrive. Stop waiting for it.
593 resetPendingAppSwitchLocked(false);
594 isAppSwitchDue = false;
595 }
596
597 // Synthesize a key repeat if appropriate.
598 if (mKeyRepeatState.lastKeyEntry) {
599 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
600 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
601 } else {
602 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
603 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
604 }
605 }
606 }
607
608 // Nothing to do if there is no pending event.
609 if (!mPendingEvent) {
610 return;
611 }
612 } else {
613 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700614 mPendingEvent = mInboundQueue.front();
615 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 traceInboundQueueLengthLocked();
617 }
618
619 // Poke user activity for this event.
620 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700621 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
624
625 // Now we have an event to dispatch.
626 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700627 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700629 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700631 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700633 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 }
635
636 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700637 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 }
639
640 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700641 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 ConfigurationChangedEntry* typedEntry =
643 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
644 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700645 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700646 break;
647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700649 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
651 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700652 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 break;
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100656 case EventEntry::Type::FOCUS: {
657 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
658 dispatchFocusLocked(currentTime, typedEntry);
659 done = true;
660 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
661 break;
662 }
663
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700664 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700665 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
666 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700667 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 resetPendingAppSwitchLocked(true);
669 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700670 } else if (dropReason == DropReason::NOT_DROPPED) {
671 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700672 }
673 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700674 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700675 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700677 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
678 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 }
680 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
681 break;
682 }
683
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700684 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700685 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700686 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
687 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700689 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700690 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700692 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
693 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700694 }
695 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
696 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699
700 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700701 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700702 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
Michael Wright3a981722015-06-10 15:26:13 +0100704 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705
706 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700707 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709}
710
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700711/**
712 * Return true if the events preceding this incoming motion event should be dropped
713 * Return false otherwise (the default behaviour)
714 */
715bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700717 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718
719 // Optimize case where the current application is unresponsive and the user
720 // decides to touch a window in a different application.
721 // If the application takes too long to catch up then we drop all events preceding
722 // the touch into the other window.
723 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700724 int32_t displayId = motionEntry.displayId;
725 int32_t x = static_cast<int32_t>(
726 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
727 int32_t y = static_cast<int32_t>(
728 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
729 sp<InputWindowHandle> touchedWindowHandle =
730 findTouchedWindowAtLocked(displayId, x, y, nullptr);
731 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732 touchedWindowHandle->getApplicationToken() !=
733 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700734 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700735 ALOGI("Pruning input queue because user touched a different application while waiting "
736 "for %s",
737 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700738 return true;
739 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700740
741 // Alternatively, maybe there's a gesture monitor that could handle this event
742 std::vector<TouchedMonitor> gestureMonitors =
743 findTouchedGestureMonitorsLocked(displayId, {});
744 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
745 sp<Connection> connection =
746 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000747 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700748 // This monitor could take more input. Drop all events preceding this
749 // event, so that gesture monitor could get a chance to receive the stream
750 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
751 "responsive gesture monitor that may handle the event",
752 mAwaitedFocusedApplication->getName().c_str());
753 return true;
754 }
755 }
756 }
757
758 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
759 // yet been processed by some connections, the dispatcher will wait for these motion
760 // events to be processed before dispatching the key event. This is because these motion events
761 // may cause a new window to be launched, which the user might expect to receive focus.
762 // To prevent waiting forever for such events, just send the key to the currently focused window
763 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
764 ALOGD("Received a new pointer down event, stop waiting for events to process and "
765 "just send the pending key event to the focused window.");
766 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700767 }
768 return false;
769}
770
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 bool needWake = mInboundQueue.empty();
773 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 traceInboundQueueLengthLocked();
775
776 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700778 // Optimize app switch latency.
779 // If the application takes too long to catch up then we drop all events preceding
780 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700783 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700785 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700790 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791 mAppSwitchSawKeyDown = false;
792 needWake = true;
793 }
794 }
795 }
796 break;
797 }
798
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700800 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
801 mNextUnblockedEvent = entry;
802 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100806 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700807 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
808 break;
809 }
810 case EventEntry::Type::CONFIGURATION_CHANGED:
811 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700812 // nothing to do
813 break;
814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 }
816
817 return needWake;
818}
819
820void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
821 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700822 mRecentQueue.push_back(entry);
823 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
824 mRecentQueue.front()->release();
825 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 }
827}
828
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700830 int32_t y, TouchState* touchState,
831 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700833 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
834 LOG_ALWAYS_FATAL(
835 "Must provide a valid touch state if adding portal windows or outside targets");
836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700838 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800839 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 const InputWindowInfo* windowInfo = windowHandle->getInfo();
841 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100842 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843
844 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100845 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
846 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
847 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800849 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (portalToDisplayId != ADISPLAY_ID_NONE &&
851 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800852 if (addPortalWindows) {
853 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700854 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800855 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700856 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 // Found window.
860 return windowHandle;
861 }
862 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800863
Michael Wright44753b12020-07-08 13:48:11 +0100864 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700865 touchState->addOrUpdateWindow(windowHandle,
866 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
867 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
871 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700872 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873}
874
Garfield Tane84e6f92019-08-29 17:28:41 -0700875std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700876 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000877 std::vector<TouchedMonitor> touchedMonitors;
878
879 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
880 addGestureMonitors(monitors, touchedMonitors);
881 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
882 const InputWindowInfo* windowInfo = portalWindow->getInfo();
883 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
885 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000886 }
887 return touchedMonitors;
888}
889
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700890void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 const char* reason;
892 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 reason = "inbound event was dropped because the policy consumed it";
898 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 case DropReason::DISABLED:
900 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 ALOGI("Dropped event because input dispatch is disabled.");
902 }
903 reason = "inbound event was dropped because input dispatch is disabled";
904 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 ALOGI("Dropped event because of pending overdue app switch.");
907 reason = "inbound event was dropped because of pending overdue app switch";
908 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700909 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 ALOGI("Dropped event because the current application is not responding and the user "
911 "has started interacting with a different application.");
912 reason = "inbound event was dropped because the current application is not responding "
913 "and the user has started interacting with a different application";
914 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 ALOGI("Dropped event because it is stale.");
917 reason = "inbound event was dropped because it is stale";
918 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700919 case DropReason::NOT_DROPPED: {
920 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700925 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700926 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
928 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700931 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700932 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
933 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
935 synthesizeCancelationEventsForAllConnectionsLocked(options);
936 } else {
937 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
938 synthesizeCancelationEventsForAllConnectionsLocked(options);
939 }
940 break;
941 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100942 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700943 case EventEntry::Type::CONFIGURATION_CHANGED:
944 case EventEntry::Type::DEVICE_RESET: {
945 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
946 break;
947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 }
949}
950
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800951static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
953 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954}
955
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700956bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
957 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
958 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
959 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960}
961
962bool InputDispatcher::isAppSwitchPendingLocked() {
963 return mAppSwitchDueTime != LONG_LONG_MAX;
964}
965
966void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
967 mAppSwitchDueTime = LONG_LONG_MAX;
968
969#if DEBUG_APP_SWITCH
970 if (handled) {
971 ALOGD("App switch has arrived.");
972 } else {
973 ALOGD("App switch was abandoned.");
974 }
975#endif
976}
977
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700979 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980}
981
982bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700983 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 return false;
985 }
986
987 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700988 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700991 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
993 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700994 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 return true;
996}
997
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700998void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
999 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000}
1001
1002void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001003 while (!mInboundQueue.empty()) {
1004 EventEntry* entry = mInboundQueue.front();
1005 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 releaseInboundEventLocked(entry);
1007 }
1008 traceInboundQueueLengthLocked();
1009}
1010
1011void InputDispatcher::releasePendingEventLocked() {
1012 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001014 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016}
1017
1018void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1019 InjectionState* injectionState = entry->injectionState;
1020 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1021#if DEBUG_DISPATCH_CYCLE
1022 ALOGD("Injected inbound event was dropped.");
1023#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001024 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001027 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
1029 addRecentEventLocked(entry);
1030 entry->release();
1031}
1032
1033void InputDispatcher::resetKeyRepeatLocked() {
1034 if (mKeyRepeatState.lastKeyEntry) {
1035 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001036 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
1038}
1039
Garfield Tane84e6f92019-08-29 17:28:41 -07001040KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1042
1043 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001044 uint32_t policyFlags = entry->policyFlags &
1045 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 if (entry->refCount == 1) {
1047 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001048 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 entry->eventTime = currentTime;
1050 entry->policyFlags = policyFlags;
1051 entry->repeatCount += 1;
1052 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001054 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001055 entry->displayId, policyFlags, entry->action, entry->flags,
1056 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058
1059 mKeyRepeatState.lastKeyEntry = newEntry;
1060 entry->release();
1061
1062 entry = newEntry;
1063 }
1064 entry->syntheticRepeat = true;
1065
1066 // Increment reference count since we keep a reference to the event in
1067 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1068 entry->refCount += 1;
1069
1070 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1071 return entry;
1072}
1073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1075 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001077 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078#endif
1079
1080 // Reset key repeating in case a keyboard device was added or removed or something.
1081 resetKeyRepeatLocked();
1082
1083 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001084 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1085 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001087 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 return true;
1089}
1090
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001093 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095#endif
1096
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 options.deviceId = entry->deviceId;
1099 synthesizeCancelationEventsForAllConnectionsLocked(options);
1100 return true;
1101}
1102
Vishnu Nairad321cd2020-08-20 16:40:21 -07001103void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001104 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001105 if (mPendingEvent != nullptr) {
1106 // Move the pending event to the front of the queue. This will give the chance
1107 // for the pending event to get dispatched to the newly focused window
1108 mInboundQueue.push_front(mPendingEvent);
1109 mPendingEvent = nullptr;
1110 }
1111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001113 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001114
1115 // This event should go to the front of the queue, but behind all other focus events
1116 // Find the last focus event, and insert right after it
1117 std::deque<EventEntry*>::reverse_iterator it =
1118 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1119 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1120
1121 // Maintain the order of focus events. Insert the entry after all other focus events.
1122 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001123}
1124
1125void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001126 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001127 if (channel == nullptr) {
1128 return; // Window has gone away
1129 }
1130 InputTarget target;
1131 target.inputChannel = channel;
1132 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1133 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001134 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1135 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001136 std::string reason = std::string("reason=").append(entry->reason);
1137 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001138 dispatchEventLocked(currentTime, entry, {target});
1139}
1140
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 if (!entry->dispatchInProgress) {
1145 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1146 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1147 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1148 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001149 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 // We have seen two identical key downs in a row which indicates that the device
1151 // driver is automatically generating key repeats itself. We take note of the
1152 // repeat here, but we disable our own next key repeat timer since it is clear that
1153 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001154 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1155 // Make sure we don't get key down from a different device. If a different
1156 // device Id has same key pressed down, the new device Id will replace the
1157 // current one to hold the key repeat with repeat count reset.
1158 // In the future when got a KEY_UP on the device id, drop it and do not
1159 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1161 resetKeyRepeatLocked();
1162 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1163 } else {
1164 // Not a repeat. Save key down state in case we do see a repeat later.
1165 resetKeyRepeatLocked();
1166 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1167 }
1168 mKeyRepeatState.lastKeyEntry = entry;
1169 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001170 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1171 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1172 // The stale device releases the key, reset staleDeviceId.
1173#if DEBUG_INBOUND_EVENT_DETAILS
1174 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1175#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 resetKeyRepeatLocked();
1178 }
1179
1180 if (entry->repeatCount == 1) {
1181 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1182 } else {
1183 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1184 }
1185
1186 entry->dispatchInProgress = true;
1187
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190
1191 // Handle case where the policy asked us to try again later last time.
1192 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1193 if (currentTime < entry->interceptKeyWakeupTime) {
1194 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1195 *nextWakeupTime = entry->interceptKeyWakeupTime;
1196 }
1197 return false; // wait until next wakeup
1198 }
1199 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1200 entry->interceptKeyWakeupTime = 0;
1201 }
1202
1203 // Give the policy a chance to intercept the key.
1204 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1205 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001206 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001207 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001208 sp<IBinder> focusedWindowToken =
1209 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1210 if (focusedWindowToken != nullptr) {
1211 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001214 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 entry->refCount += 1;
1216 return false; // wait for the command to run
1217 } else {
1218 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1219 }
1220 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001221 if (*dropReason == DropReason::NOT_DROPPED) {
1222 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 }
1225
1226 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001227 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001229 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001231 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 return true;
1233 }
1234
1235 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001236 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001238 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1240 return false;
1241 }
1242
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001243 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1245 return true;
1246 }
1247
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001248 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001249 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250
1251 // Dispatch the key.
1252 dispatchEventLocked(currentTime, entry, inputTargets);
1253 return true;
1254}
1255
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001256void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001258 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1260 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001261 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1262 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1263 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264#endif
1265}
1266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001267bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1268 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001269 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 entry->dispatchInProgress = true;
1273
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276
1277 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001278 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001280 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 return true;
1283 }
1284
1285 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1286
1287 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001288 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
1290 bool conflictingPointerActions = false;
1291 int32_t injectionResult;
1292 if (isPointerEvent) {
1293 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 } else {
1298 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 }
1302 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1303 return false;
1304 }
1305
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001306 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001307 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1308 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1309 return true;
1310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001312 CancelationOptions::Mode mode(isPointerEvent
1313 ? CancelationOptions::CANCEL_POINTER_EVENTS
1314 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1315 CancelationOptions options(mode, "input event injection failed");
1316 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 return true;
1318 }
1319
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001320 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001323 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001324 std::unordered_map<int32_t, TouchState>::iterator it =
1325 mTouchStatesByDisplay.find(entry->displayId);
1326 if (it != mTouchStatesByDisplay.end()) {
1327 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001328 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001329 // The event has gone through these portal windows, so we add monitoring targets of
1330 // the corresponding displays as well.
1331 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001332 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001333 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001334 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001335 }
1336 }
1337 }
1338 }
1339
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 // Dispatch the motion.
1341 if (conflictingPointerActions) {
1342 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001343 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 synthesizeCancelationEventsForAllConnectionsLocked(options);
1345 }
1346 dispatchEventLocked(currentTime, entry, inputTargets);
1347 return true;
1348}
1349
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001350void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001352 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353 ", policyFlags=0x%x, "
1354 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1355 "metaState=0x%x, buttonState=0x%x,"
1356 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1358 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1359 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001361 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 "x=%f, y=%f, pressure=%f, size=%f, "
1364 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1365 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001366 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1367 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1368 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1369 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1370 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1371 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1372 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1373 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1374 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1375 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377#endif
1378}
1379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1381 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001382 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383#if DEBUG_DISPATCH_CYCLE
1384 ALOGD("dispatchEventToCurrentInputTargets");
1385#endif
1386
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001387 updateInteractionTokensLocked(*eventEntry, inputTargets);
1388
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1390
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001393 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001394 sp<Connection> connection =
1395 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001396 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001397 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001399 if (DEBUG_FOCUS) {
1400 ALOGD("Dropping event delivery to target with channel '%s' because it "
1401 "is no longer registered with the input dispatcher.",
1402 inputTarget.inputChannel->getName().c_str());
1403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 }
1405 }
1406}
1407
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001408void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1409 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1410 // If the policy decides to close the app, we will get a channel removal event via
1411 // unregisterInputChannel, and will clean up the connection that way. We are already not
1412 // sending new pointers to the connection when it blocked, but focused events will continue to
1413 // pile up.
1414 ALOGW("Canceling events for %s because it is unresponsive",
1415 connection->inputChannel->getName().c_str());
1416 if (connection->status == Connection::STATUS_NORMAL) {
1417 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1418 "application not responding");
1419 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421}
1422
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001423void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001424 if (DEBUG_FOCUS) {
1425 ALOGD("Resetting ANR timeouts.");
1426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427
1428 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001429 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001430 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431}
1432
Tiger Huang721e26f2018-07-24 22:26:19 +08001433/**
1434 * Get the display id that the given event should go to. If this event specifies a valid display id,
1435 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1436 * Focused display is the display that the user most recently interacted with.
1437 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001438int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001439 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001440 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001441 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001442 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1443 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 break;
1445 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001446 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001447 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1448 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 break;
1450 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001451 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001452 case EventEntry::Type::CONFIGURATION_CHANGED:
1453 case EventEntry::Type::DEVICE_RESET: {
1454 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 return ADISPLAY_ID_NONE;
1456 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001457 }
1458 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1459}
1460
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001461bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1462 const char* focusedWindowName) {
1463 if (mAnrTracker.empty()) {
1464 // already processed all events that we waited for
1465 mKeyIsWaitingForEventsTimeout = std::nullopt;
1466 return false;
1467 }
1468
1469 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1470 // Start the timer
1471 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1472 "focus to change",
1473 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001474 mKeyIsWaitingForEventsTimeout = currentTime +
1475 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1476 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001477 return true;
1478 }
1479
1480 // We still have pending events, and already started the timer
1481 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1482 return true; // Still waiting
1483 }
1484
1485 // Waited too long, and some connection still hasn't processed all motions
1486 // Just send the key to the focused window
1487 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1488 focusedWindowName);
1489 mKeyIsWaitingForEventsTimeout = std::nullopt;
1490 return false;
1491}
1492
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001494 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 std::vector<InputTarget>& inputTargets,
1496 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001497 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498
Tiger Huang721e26f2018-07-24 22:26:19 +08001499 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001500 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001501 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001502 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1503
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 // If there is no currently focused window and no focused application
1505 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001506 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1507 ALOGI("Dropping %s event because there is no focused window or focused application in "
1508 "display %" PRId32 ".",
1509 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001510 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001513 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1514 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1515 // start interacting with another application via touch (app switch). This code can be removed
1516 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1517 // an app is expected to have a focused window.
1518 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1519 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1520 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001521 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1522 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1523 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001524 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001525 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001526 ALOGW("Waiting because no window has focus but %s may eventually add a "
1527 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001528 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001529 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1530 return INPUT_EVENT_INJECTION_PENDING;
1531 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1532 // Already raised ANR. Drop the event
1533 ALOGE("Dropping %s event because there is no focused window",
1534 EventEntry::typeToString(entry.type));
1535 return INPUT_EVENT_INJECTION_FAILED;
1536 } else {
1537 // Still waiting for the focused window
1538 return INPUT_EVENT_INJECTION_PENDING;
1539 }
1540 }
1541
1542 // we have a valid, non-null focused window
1543 resetNoFocusedWindowTimeoutLocked();
1544
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001546 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001547 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
1549
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001550 if (focusedWindowHandle->getInfo()->paused) {
1551 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1552 return INPUT_EVENT_INJECTION_PENDING;
1553 }
1554
1555 // If the event is a key event, then we must wait for all previous events to
1556 // complete before delivering it because previous events may have the
1557 // side-effect of transferring focus to a different window and we want to
1558 // ensure that the following keys are sent to the new window.
1559 //
1560 // Suppose the user touches a button in a window then immediately presses "A".
1561 // If the button causes a pop-up window to appear then we want to ensure that
1562 // the "A" key is delivered to the new pop-up window. This is because users
1563 // often anticipate pending UI changes when typing on a keyboard.
1564 // To obtain this behavior, we must serialize key events with respect to all
1565 // prior input events.
1566 if (entry.type == EventEntry::Type::KEY) {
1567 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1568 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1569 return INPUT_EVENT_INJECTION_PENDING;
1570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572
1573 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001574 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001575 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1576 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
1578 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001579 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580}
1581
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001582/**
1583 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1584 * that are currently unresponsive.
1585 */
1586std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1587 const std::vector<TouchedMonitor>& monitors) const {
1588 std::vector<TouchedMonitor> responsiveMonitors;
1589 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1590 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1591 sp<Connection> connection = getConnectionLocked(
1592 monitor.monitor.inputChannel->getConnectionToken());
1593 if (connection == nullptr) {
1594 ALOGE("Could not find connection for monitor %s",
1595 monitor.monitor.inputChannel->getName().c_str());
1596 return false;
1597 }
1598 if (!connection->responsive) {
1599 ALOGW("Unresponsive monitor %s will not get the new gesture",
1600 connection->inputChannel->getName().c_str());
1601 return false;
1602 }
1603 return true;
1604 });
1605 return responsiveMonitors;
1606}
1607
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 std::vector<InputTarget>& inputTargets,
1611 nsecs_t* nextWakeupTime,
1612 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001613 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 enum InjectionPermission {
1615 INJECTION_PERMISSION_UNKNOWN,
1616 INJECTION_PERMISSION_GRANTED,
1617 INJECTION_PERMISSION_DENIED
1618 };
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 // For security reasons, we defer updating the touch state until we are sure that
1621 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001622 int32_t displayId = entry.displayId;
1623 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1625
1626 // Update the touch state as needed based on the properties of the touch event.
1627 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1628 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001629 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1630 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001632 // Copy current touch state into tempTouchState.
1633 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1634 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001635 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001636 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001637 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1638 mTouchStatesByDisplay.find(displayId);
1639 if (oldStateIt != mTouchStatesByDisplay.end()) {
1640 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001641 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001642 }
1643
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001644 bool isSplit = tempTouchState.split;
1645 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1646 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1647 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1649 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1650 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1651 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1652 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 bool wrongDevice = false;
1655 if (newGesture) {
1656 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001657 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001658 ALOGI("Dropping event because a pointer for a different device is already down "
1659 "in display %" PRId32,
1660 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001661 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1663 switchedDevice = false;
1664 wrongDevice = true;
1665 goto Failed;
1666 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001667 tempTouchState.reset();
1668 tempTouchState.down = down;
1669 tempTouchState.deviceId = entry.deviceId;
1670 tempTouchState.source = entry.source;
1671 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001673 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001674 ALOGI("Dropping move event because a pointer for a different device is already active "
1675 "in display %" PRId32,
1676 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001677 // TODO: test multiple simultaneous input streams.
1678 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1679 switchedDevice = false;
1680 wrongDevice = true;
1681 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
1683
1684 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1685 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1686
Garfield Tan00f511d2019-06-12 16:55:40 -07001687 int32_t x;
1688 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001690 // Always dispatch mouse events to cursor position.
1691 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692 x = int32_t(entry.xCursorPosition);
1693 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001694 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001695 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1696 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001697 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001698 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001699 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001700 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1701 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001702
1703 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001704 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001708 if (newTouchedWindowHandle != nullptr &&
1709 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001710 // New window supports splitting, but we should never split mouse events.
1711 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 } else if (isSplit) {
1713 // New window does not support splitting but we have already split events.
1714 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001715 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717
1718 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001719 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001721 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001722 }
1723
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001724 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1725 ALOGI("Not sending touch event to %s because it is paused",
1726 newTouchedWindowHandle->getName().c_str());
1727 newTouchedWindowHandle = nullptr;
1728 }
1729
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001730 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001732 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1733 if (!isResponsive) {
1734 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001735 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1736 newTouchedWindowHandle = nullptr;
1737 }
1738 }
1739
1740 // Also don't send the new touch event to unresponsive gesture monitors
1741 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1742
Michael Wright3dd60e22019-03-27 22:06:44 +00001743 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1744 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001745 "(%d, %d) in display %" PRId32 ".",
1746 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001747 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1748 goto Failed;
1749 }
1750
1751 if (newTouchedWindowHandle != nullptr) {
1752 // Set target flags.
1753 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1754 if (isSplit) {
1755 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001757 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1758 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1759 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1760 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1761 }
1762
1763 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001764 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1765 newHoverWindowHandle = nullptr;
1766 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001767 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001768 }
1769
1770 // Update the temporary touch state.
1771 BitSet32 pointerIds;
1772 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001773 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001774 pointerIds.markBit(pointerId);
1775 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001776 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001779 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 } else {
1781 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1782
1783 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001784 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001785 if (DEBUG_FOCUS) {
1786 ALOGD("Dropping event because the pointer is not down or we previously "
1787 "dropped the pointer down event in display %" PRId32,
1788 displayId);
1789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1791 goto Failed;
1792 }
1793
1794 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001796 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1798 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799
1800 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001801 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001802 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001803 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1804 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001805 if (DEBUG_FOCUS) {
1806 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1807 oldTouchedWindowHandle->getName().c_str(),
1808 newTouchedWindowHandle->getName().c_str(), displayId);
1809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001811 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1812 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1813 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814
1815 // Make a slippery entrance into the new window.
1816 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1817 isSplit = true;
1818 }
1819
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 int32_t targetFlags =
1821 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 if (isSplit) {
1823 targetFlags |= InputTarget::FLAG_SPLIT;
1824 }
1825 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1826 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1827 }
1828
1829 BitSet32 pointerIds;
1830 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 }
1835 }
1836 }
1837
1838 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001839 // Let the previous window know that the hover sequence is over, unless we already did it
1840 // when dispatching it as is to newTouchedWindowHandle.
1841 if (mLastHoverWindowHandle != nullptr &&
1842 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1843 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844#if DEBUG_HOVER
1845 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001846 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001848 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1849 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 }
1851
Garfield Tandf26e862020-07-01 20:18:19 -07001852 // Let the new window know that the hover sequence is starting, unless we already did it
1853 // when dispatching it as is to newTouchedWindowHandle.
1854 if (newHoverWindowHandle != nullptr &&
1855 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1856 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857#if DEBUG_HOVER
1858 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001859 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1862 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1863 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
1865 }
1866
1867 // Check permission to inject into all touched foreground windows and ensure there
1868 // is at least one touched foreground window.
1869 {
1870 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001871 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1873 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001874 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1876 injectionPermission = INJECTION_PERMISSION_DENIED;
1877 goto Failed;
1878 }
1879 }
1880 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001881 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001882 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001883 ALOGI("Dropping event because there is no touched foreground window in display "
1884 "%" PRId32 " or gesture monitor to receive it.",
1885 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1887 goto Failed;
1888 }
1889
1890 // Permission granted to injection into all touched foreground windows.
1891 injectionPermission = INJECTION_PERMISSION_GRANTED;
1892 }
1893
1894 // Check whether windows listening for outside touches are owned by the same UID. If it is
1895 // set the policy flag that we will not reveal coordinate information to this window.
1896 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1897 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001899 if (foregroundWindowHandle) {
1900 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001901 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001902 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1903 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1904 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001905 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1906 InputTarget::FLAG_ZERO_COORDS,
1907 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910 }
1911 }
1912 }
1913
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // If this is the first pointer going down and the touched window has a wallpaper
1915 // then also add the touched wallpaper windows so they are locked in for the duration
1916 // of the touch gesture.
1917 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1918 // engine only supports touch events. We would need to add a mechanism similar
1919 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1920 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1921 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001923 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001924 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001925 getWindowHandlesLocked(displayId);
1926 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001929 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001930 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001931 .addOrUpdateWindow(windowHandle,
1932 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1933 InputTarget::
1934 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1935 InputTarget::FLAG_DISPATCH_AS_IS,
1936 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
1938 }
1939 }
1940 }
1941
1942 // Success! Output targets.
1943 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1944
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001945 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
1949
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001950 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001951 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001952 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 }
1954
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 // Drop the outside or hover touch windows since we will not care about them
1956 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001957 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
1959Failed:
1960 // Check injection permission once and for all.
1961 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001962 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 injectionPermission = INJECTION_PERMISSION_GRANTED;
1964 } else {
1965 injectionPermission = INJECTION_PERMISSION_DENIED;
1966 }
1967 }
1968
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001969 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1970 return injectionResult;
1971 }
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001974 if (!wrongDevice) {
1975 if (switchedDevice) {
1976 if (DEBUG_FOCUS) {
1977 ALOGD("Conflicting pointer actions: Switched to a different device.");
1978 }
1979 *outConflictingPointerActions = true;
1980 }
1981
1982 if (isHoverAction) {
1983 // Started hovering, therefore no longer down.
1984 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001985 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1987 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 *outConflictingPointerActions = true;
1990 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 tempTouchState.reset();
1992 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1993 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1994 tempTouchState.deviceId = entry.deviceId;
1995 tempTouchState.source = entry.source;
1996 tempTouchState.displayId = displayId;
1997 }
1998 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1999 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2000 // All pointers up or canceled.
2001 tempTouchState.reset();
2002 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2003 // First pointer went down.
2004 if (oldState && oldState->down) {
2005 if (DEBUG_FOCUS) {
2006 ALOGD("Conflicting pointer actions: Down received while already down.");
2007 }
2008 *outConflictingPointerActions = true;
2009 }
2010 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2011 // One pointer went up.
2012 if (isSplit) {
2013 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2014 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002016 for (size_t i = 0; i < tempTouchState.windows.size();) {
2017 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2018 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2019 touchedWindow.pointerIds.clearBit(pointerId);
2020 if (touchedWindow.pointerIds.isEmpty()) {
2021 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2022 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002025 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002027 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002028 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002029
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002030 // Save changes unless the action was scroll in which case the temporary touch
2031 // state was only valid for this one action.
2032 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2033 if (tempTouchState.displayId >= 0) {
2034 mTouchStatesByDisplay[displayId] = tempTouchState;
2035 } else {
2036 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002040 // Update hover state.
2041 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 return injectionResult;
2045}
2046
2047void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048 int32_t targetFlags, BitSet32 pointerIds,
2049 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002050 std::vector<InputTarget>::iterator it =
2051 std::find_if(inputTargets.begin(), inputTargets.end(),
2052 [&windowHandle](const InputTarget& inputTarget) {
2053 return inputTarget.inputChannel->getConnectionToken() ==
2054 windowHandle->getToken();
2055 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002056
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002057 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002058
2059 if (it == inputTargets.end()) {
2060 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002061 std::shared_ptr<InputChannel> inputChannel =
2062 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002063 if (inputChannel == nullptr) {
2064 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2065 return;
2066 }
2067 inputTarget.inputChannel = inputChannel;
2068 inputTarget.flags = targetFlags;
2069 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2070 inputTargets.push_back(inputTarget);
2071 it = inputTargets.end() - 1;
2072 }
2073
2074 ALOG_ASSERT(it->flags == targetFlags);
2075 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2076
chaviw1ff3d1e2020-07-01 15:53:47 -07002077 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078}
2079
Michael Wright3dd60e22019-03-27 22:06:44 +00002080void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002081 int32_t displayId, float xOffset,
2082 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002083 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2084 mGlobalMonitorsByDisplay.find(displayId);
2085
2086 if (it != mGlobalMonitorsByDisplay.end()) {
2087 const std::vector<Monitor>& monitors = it->second;
2088 for (const Monitor& monitor : monitors) {
2089 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092}
2093
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2095 float yOffset,
2096 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002097 InputTarget target;
2098 target.inputChannel = monitor.inputChannel;
2099 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002100 ui::Transform t;
2101 t.set(xOffset, yOffset);
2102 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002103 inputTargets.push_back(target);
2104}
2105
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107 const InjectionState* injectionState) {
2108 if (injectionState &&
2109 (windowHandle == nullptr ||
2110 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2111 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002112 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114 "owned by uid %d",
2115 injectionState->injectorPid, injectionState->injectorUid,
2116 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 } else {
2118 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121 return false;
2122 }
2123 return true;
2124}
2125
Robert Carrc9bf1d32020-04-13 17:21:08 -07002126/**
2127 * Indicate whether one window handle should be considered as obscuring
2128 * another window handle. We only check a few preconditions. Actually
2129 * checking the bounds is left to the caller.
2130 */
2131static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2132 const sp<InputWindowHandle>& otherHandle) {
2133 // Compare by token so cloned layers aren't counted
2134 if (haveSameToken(windowHandle, otherHandle)) {
2135 return false;
2136 }
2137 auto info = windowHandle->getInfo();
2138 auto otherInfo = otherHandle->getInfo();
2139 if (!otherInfo->visible) {
2140 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002141 } else if (info->ownerUid == otherInfo->ownerUid) {
2142 // If ownerUid is the same we don't generate occlusion events as there
2143 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002144 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002145 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002146 return false;
2147 } else if (otherInfo->displayId != info->displayId) {
2148 return false;
2149 }
2150 return true;
2151}
2152
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2154 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002156 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002157 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002158 if (windowHandle == otherHandle) {
2159 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002162 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002163 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 return true;
2165 }
2166 }
2167 return false;
2168}
2169
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002170bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2171 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002172 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002173 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002174 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002175 if (windowHandle == otherHandle) {
2176 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002177 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002178 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002179 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002180 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002181 return true;
2182 }
2183 }
2184 return false;
2185}
2186
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002187std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002188 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002190 if (applicationHandle != nullptr) {
2191 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002192 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 } else {
2194 return applicationHandle->getName();
2195 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002196 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002197 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002199 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201}
2202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002204 if (eventEntry.type == EventEntry::Type::FOCUS) {
2205 // Focus events are passed to apps, but do not represent user activity.
2206 return;
2207 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002208 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002209 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002210 if (focusedWindowHandle != nullptr) {
2211 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002212 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002214 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215#endif
2216 return;
2217 }
2218 }
2219
2220 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002221 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002222 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002223 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2224 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 return;
2226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002228 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 eventType = USER_ACTIVITY_EVENT_TOUCH;
2230 }
2231 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002233 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002234 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2235 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 return;
2237 }
2238 eventType = USER_ACTIVITY_EVENT_BUTTON;
2239 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002241 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002242 case EventEntry::Type::CONFIGURATION_CHANGED:
2243 case EventEntry::Type::DEVICE_RESET: {
2244 LOG_ALWAYS_FATAL("%s events are not user activity",
2245 EventEntry::typeToString(eventEntry.type));
2246 break;
2247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 }
2249
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002250 std::unique_ptr<CommandEntry> commandEntry =
2251 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002254 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255}
2256
2257void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 const sp<Connection>& connection,
2259 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002260 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002261 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002263 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002264 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002265 ATRACE_NAME(message.c_str());
2266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267#if DEBUG_DISPATCH_CYCLE
2268 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002269 "globalScaleFactor=%f, pointerIds=0x%x %s",
2270 connection->getInputChannelName().c_str(), inputTarget.flags,
2271 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2272 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273#endif
2274
2275 // Skip this event if the connection status is not normal.
2276 // We don't want to enqueue additional outbound events if the connection is broken.
2277 if (connection->status != Connection::STATUS_NORMAL) {
2278#if DEBUG_DISPATCH_CYCLE
2279 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281#endif
2282 return;
2283 }
2284
2285 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002286 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2287 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2288 "Entry type %s should not have FLAG_SPLIT",
2289 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002291 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002292 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002294 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 if (!splitMotionEntry) {
2296 return; // split event was dropped
2297 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002298 if (DEBUG_FOCUS) {
2299 ALOGD("channel '%s' ~ Split motion event.",
2300 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002301 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002302 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 splitMotionEntry->release();
2305 return;
2306 }
2307 }
2308
2309 // Not splitting. Enqueue dispatch entries for the event as is.
2310 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2311}
2312
2313void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002314 const sp<Connection>& connection,
2315 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002316 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002319 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002320 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002321 ATRACE_NAME(message.c_str());
2322 }
2323
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002324 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325
2326 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002327 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002329 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002331 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002333 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002335 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002337 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002338 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339
2340 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002341 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 startDispatchCycleLocked(currentTime, connection);
2343 }
2344}
2345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2347 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002348 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002350 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002351 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2352 connection->getInputChannelName().c_str(),
2353 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002354 ATRACE_NAME(message.c_str());
2355 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002356 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 if (!(inputTargetFlags & dispatchMode)) {
2358 return;
2359 }
2360 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2361
2362 // This is a new event.
2363 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002364 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002365 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002367 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2368 // different EventEntry than what was passed in.
2369 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002371 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002372 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002373 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002374 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002375 dispatchEntry->resolvedAction = keyEntry.action;
2376 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002378 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2379 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2382 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 return; // skip the inconsistent event
2385 }
2386 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002389 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002390 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002391 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2392 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2393 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2394 static_cast<int32_t>(IdGenerator::Source::OTHER);
2395 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002396 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2397 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2398 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2399 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2400 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2401 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2402 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2403 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2404 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2405 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2406 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002407 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002408 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002409 }
2410 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2412 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2415 "event",
2416 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002418 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002421 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002422 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2423 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2424 }
2425 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2426 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2430 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2433 "event",
2434 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002436 return; // skip the inconsistent event
2437 }
2438
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002439 dispatchEntry->resolvedEventId =
2440 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2441 ? mIdGenerator.nextId()
2442 : motionEntry.id;
2443 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2444 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2445 ") to MotionEvent(id=0x%" PRIx32 ").",
2446 motionEntry.id, dispatchEntry->resolvedEventId);
2447 ATRACE_NAME(message.c_str());
2448 }
2449
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002450 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002451 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452
2453 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002455 case EventEntry::Type::FOCUS: {
2456 break;
2457 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002458 case EventEntry::Type::CONFIGURATION_CHANGED:
2459 case EventEntry::Type::DEVICE_RESET: {
2460 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002461 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002462 break;
2463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
2466 // Remember that we are waiting for this dispatch to complete.
2467 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002468 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
2471 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002472 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002473 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002474}
2475
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002476/**
2477 * This function is purely for debugging. It helps us understand where the user interaction
2478 * was taking place. For example, if user is touching launcher, we will see a log that user
2479 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2480 * We will see both launcher and wallpaper in that list.
2481 * Once the interaction with a particular set of connections starts, no new logs will be printed
2482 * until the set of interacted connections changes.
2483 *
2484 * The following items are skipped, to reduce the logspam:
2485 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2486 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2487 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2488 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2489 * Both of those ACTION_UP events would not be logged
2490 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2491 * will not be logged. This is omitted to reduce the amount of data printed.
2492 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2493 * gesture monitor is the only connection receiving the remainder of the gesture.
2494 */
2495void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2496 const std::vector<InputTarget>& targets) {
2497 // Skip ACTION_UP events, and all events other than keys and motions
2498 if (entry.type == EventEntry::Type::KEY) {
2499 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2500 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2501 return;
2502 }
2503 } else if (entry.type == EventEntry::Type::MOTION) {
2504 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2505 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2506 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2507 return;
2508 }
2509 } else {
2510 return; // Not a key or a motion
2511 }
2512
2513 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2514 std::vector<sp<Connection>> newConnections;
2515 for (const InputTarget& target : targets) {
2516 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2517 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2518 continue; // Skip windows that receive ACTION_OUTSIDE
2519 }
2520
2521 sp<IBinder> token = target.inputChannel->getConnectionToken();
2522 sp<Connection> connection = getConnectionLocked(token);
2523 if (connection == nullptr || connection->monitor) {
2524 continue; // We only need to keep track of the non-monitor connections.
2525 }
2526 newConnectionTokens.insert(std::move(token));
2527 newConnections.emplace_back(connection);
2528 }
2529 if (newConnectionTokens == mInteractionConnectionTokens) {
2530 return; // no change
2531 }
2532 mInteractionConnectionTokens = newConnectionTokens;
2533
2534 std::string windowList;
2535 for (const sp<Connection>& connection : newConnections) {
2536 windowList += connection->getWindowName() + ", ";
2537 }
2538 std::string message = "Interaction with windows: " + windowList;
2539 if (windowList.empty()) {
2540 message += "<none>";
2541 }
2542 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2543}
2544
chaviwfd6d3512019-03-25 13:23:49 -07002545void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002546 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002547 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002548 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2549 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002550 return;
2551 }
2552
Vishnu Nairad321cd2020-08-20 16:40:21 -07002553 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2554 if (focusedToken == token) {
2555 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002556 return;
2557 }
2558
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002559 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2560 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002561 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002562 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563}
2564
2565void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002567 if (ATRACE_ENABLED()) {
2568 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002570 ATRACE_NAME(message.c_str());
2571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574#endif
2575
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002576 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2577 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002579 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002580 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002581 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582
2583 // Publish the event.
2584 status_t status;
2585 EventEntry* eventEntry = dispatchEntry->eventEntry;
2586 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002587 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002588 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2589 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002592 status =
2593 connection->inputPublisher
2594 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2595 keyEntry->deviceId, keyEntry->source,
2596 keyEntry->displayId, std::move(hmac),
2597 dispatchEntry->resolvedAction,
2598 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2599 keyEntry->scanCode, keyEntry->metaState,
2600 keyEntry->repeatCount, keyEntry->downTime,
2601 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002605 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 PointerCoords scaledCoords[MAX_POINTERS];
2609 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2610
chaviw82357092020-01-28 13:13:06 -08002611 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2613 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2614 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002615 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002616 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2617 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002618 // Don't apply window scale here since we don't want scale to affect raw
2619 // coordinates. The scale will be sent back to the client and applied
2620 // later when requesting relative coordinates.
2621 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2622 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 }
2624 usingCoords = scaledCoords;
2625 }
2626 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 // We don't want the dispatch target to know.
2628 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2629 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2630 scaledCoords[i].clear();
2631 }
2632 usingCoords = scaledCoords;
2633 }
2634 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002635
2636 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002637
2638 // Publish the motion event.
2639 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002640 .publishMotionEvent(dispatchEntry->seq,
2641 dispatchEntry->resolvedEventId,
2642 motionEntry->deviceId, motionEntry->source,
2643 motionEntry->displayId, std::move(hmac),
2644 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 motionEntry->actionButton,
2646 dispatchEntry->resolvedFlags,
2647 motionEntry->edgeFlags, motionEntry->metaState,
2648 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002649 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002650 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002651 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 motionEntry->yPrecision,
2653 motionEntry->xCursorPosition,
2654 motionEntry->yCursorPosition,
2655 motionEntry->downTime, motionEntry->eventTime,
2656 motionEntry->pointerCount,
2657 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002658 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 break;
2660 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002661 case EventEntry::Type::FOCUS: {
2662 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2663 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002664 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002665 focusEntry->hasFocus,
2666 mInTouchMode);
2667 break;
2668 }
2669
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002670 case EventEntry::Type::CONFIGURATION_CHANGED:
2671 case EventEntry::Type::DEVICE_RESET: {
2672 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2673 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677
2678 // Check the result.
2679 if (status) {
2680 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002681 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002683 "This is unexpected because the wait queue is empty, so the pipe "
2684 "should be empty and we shouldn't have any problems writing an "
2685 "event to it, status=%d",
2686 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2688 } else {
2689 // Pipe is full and we are waiting for the app to finish process some events
2690 // before sending more events to it.
2691#if DEBUG_DISPATCH_CYCLE
2692 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 "waiting for the application to catch up",
2694 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 }
2697 } else {
2698 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002699 "status=%d",
2700 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2702 }
2703 return;
2704 }
2705
2706 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002707 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2708 connection->outboundQueue.end(),
2709 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002710 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002711 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002712 if (connection->responsive) {
2713 mAnrTracker.insert(dispatchEntry->timeoutTime,
2714 connection->inputChannel->getConnectionToken());
2715 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002716 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 }
2718}
2719
chaviw09c8d2d2020-08-24 15:48:26 -07002720std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2721 size_t size;
2722 switch (event.type) {
2723 case VerifiedInputEvent::Type::KEY: {
2724 size = sizeof(VerifiedKeyEvent);
2725 break;
2726 }
2727 case VerifiedInputEvent::Type::MOTION: {
2728 size = sizeof(VerifiedMotionEvent);
2729 break;
2730 }
2731 }
2732 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2733 return mHmacKeyManager.sign(start, size);
2734}
2735
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002736const std::array<uint8_t, 32> InputDispatcher::getSignature(
2737 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2738 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2739 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2740 // Only sign events up and down events as the purely move events
2741 // are tied to their up/down counterparts so signing would be redundant.
2742 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2743 verifiedEvent.actionMasked = actionMasked;
2744 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002745 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002746 }
2747 return INVALID_HMAC;
2748}
2749
2750const std::array<uint8_t, 32> InputDispatcher::getSignature(
2751 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2752 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2753 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2754 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002755 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002756}
2757
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 const sp<Connection>& connection, uint32_t seq,
2760 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761#if DEBUG_DISPATCH_CYCLE
2762 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764#endif
2765
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002766 if (connection->status == Connection::STATUS_BROKEN ||
2767 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 return;
2769 }
2770
2771 // Notify other system components and prepare to start the next dispatch cycle.
2772 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2773}
2774
2775void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 const sp<Connection>& connection,
2777 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778#if DEBUG_DISPATCH_CYCLE
2779 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781#endif
2782
2783 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002784 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002785 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002786 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002787 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
2789 // The connection appears to be unrecoverably broken.
2790 // Ignore already broken or zombie connections.
2791 if (connection->status == Connection::STATUS_NORMAL) {
2792 connection->status = Connection::STATUS_BROKEN;
2793
2794 if (notify) {
2795 // Notify other system components.
2796 onDispatchCycleBrokenLocked(currentTime, connection);
2797 }
2798 }
2799}
2800
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002801void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2802 while (!queue.empty()) {
2803 DispatchEntry* dispatchEntry = queue.front();
2804 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002805 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 }
2807}
2808
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002809void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002811 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813 delete dispatchEntry;
2814}
2815
2816int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2817 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2818
2819 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002820 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002822 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 "fd=%d, events=0x%x",
2825 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return 0; // remove the callback
2827 }
2828
2829 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002830 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2832 if (!(events & ALOOPER_EVENT_INPUT)) {
2833 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 "events=0x%x",
2835 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 return 1;
2837 }
2838
2839 nsecs_t currentTime = now();
2840 bool gotOne = false;
2841 status_t status;
2842 for (;;) {
2843 uint32_t seq;
2844 bool handled;
2845 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2846 if (status) {
2847 break;
2848 }
2849 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2850 gotOne = true;
2851 }
2852 if (gotOne) {
2853 d->runCommandsLockedInterruptible();
2854 if (status == WOULD_BLOCK) {
2855 return 1;
2856 }
2857 }
2858
2859 notify = status != DEAD_OBJECT || !connection->monitor;
2860 if (notify) {
2861 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
2864 } else {
2865 // Monitor channels are never explicitly unregistered.
2866 // We do it automatically when the remote endpoint is closed so don't warn
2867 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002868 const bool stillHaveWindowHandle =
2869 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2870 nullptr;
2871 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 if (notify) {
2873 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002874 "events=0x%x",
2875 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 }
2877 }
2878
Garfield Tan15601662020-09-22 15:32:38 -07002879 // Remove the channel.
2880 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883}
2884
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002887 for (const auto& pair : mConnectionsByFd) {
2888 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 }
2890}
2891
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002893 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002894 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2895 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2896}
2897
2898void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2899 const CancelationOptions& options,
2900 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2901 for (const auto& it : monitorsByDisplay) {
2902 const std::vector<Monitor>& monitors = it.second;
2903 for (const Monitor& monitor : monitors) {
2904 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002905 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002906 }
2907}
2908
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002910 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002911 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002912 if (connection == nullptr) {
2913 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002915
2916 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917}
2918
2919void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2920 const sp<Connection>& connection, const CancelationOptions& options) {
2921 if (connection->status == Connection::STATUS_BROKEN) {
2922 return;
2923 }
2924
2925 nsecs_t currentTime = now();
2926
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002927 std::vector<EventEntry*> cancelationEvents =
2928 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002930 if (cancelationEvents.empty()) {
2931 return;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002934 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2935 "with reality: %s, mode=%d.",
2936 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2937 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002939
2940 InputTarget target;
2941 sp<InputWindowHandle> windowHandle =
2942 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2943 if (windowHandle != nullptr) {
2944 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002945 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002946 target.globalScaleFactor = windowInfo->globalScaleFactor;
2947 }
2948 target.inputChannel = connection->inputChannel;
2949 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2950
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002951 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2952 EventEntry* cancelationEventEntry = cancelationEvents[i];
2953 switch (cancelationEventEntry->type) {
2954 case EventEntry::Type::KEY: {
2955 logOutboundKeyDetails("cancel - ",
2956 static_cast<const KeyEntry&>(*cancelationEventEntry));
2957 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002959 case EventEntry::Type::MOTION: {
2960 logOutboundMotionDetails("cancel - ",
2961 static_cast<const MotionEntry&>(*cancelationEventEntry));
2962 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002964 case EventEntry::Type::FOCUS: {
2965 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2966 break;
2967 }
2968 case EventEntry::Type::CONFIGURATION_CHANGED:
2969 case EventEntry::Type::DEVICE_RESET: {
2970 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2971 EventEntry::typeToString(cancelationEventEntry->type));
2972 break;
2973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 }
2975
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002976 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2977 target, InputTarget::FLAG_DISPATCH_AS_IS);
2978
2979 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002981
2982 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983}
2984
Svet Ganov5d3bc372020-01-26 23:11:07 -08002985void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2986 const sp<Connection>& connection) {
2987 if (connection->status == Connection::STATUS_BROKEN) {
2988 return;
2989 }
2990
2991 nsecs_t currentTime = now();
2992
2993 std::vector<EventEntry*> downEvents =
2994 connection->inputState.synthesizePointerDownEvents(currentTime);
2995
2996 if (downEvents.empty()) {
2997 return;
2998 }
2999
3000#if DEBUG_OUTBOUND_EVENT_DETAILS
3001 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3002 connection->getInputChannelName().c_str(), downEvents.size());
3003#endif
3004
3005 InputTarget target;
3006 sp<InputWindowHandle> windowHandle =
3007 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3008 if (windowHandle != nullptr) {
3009 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003010 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003011 target.globalScaleFactor = windowInfo->globalScaleFactor;
3012 }
3013 target.inputChannel = connection->inputChannel;
3014 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3015
3016 for (EventEntry* downEventEntry : downEvents) {
3017 switch (downEventEntry->type) {
3018 case EventEntry::Type::MOTION: {
3019 logOutboundMotionDetails("down - ",
3020 static_cast<const MotionEntry&>(*downEventEntry));
3021 break;
3022 }
3023
3024 case EventEntry::Type::KEY:
3025 case EventEntry::Type::FOCUS:
3026 case EventEntry::Type::CONFIGURATION_CHANGED:
3027 case EventEntry::Type::DEVICE_RESET: {
3028 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3029 EventEntry::typeToString(downEventEntry->type));
3030 break;
3031 }
3032 }
3033
3034 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3035 target, InputTarget::FLAG_DISPATCH_AS_IS);
3036
3037 downEventEntry->release();
3038 }
3039
3040 startDispatchCycleLocked(currentTime, connection);
3041}
3042
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003043MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003044 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 ALOG_ASSERT(pointerIds.value != 0);
3046
3047 uint32_t splitPointerIndexMap[MAX_POINTERS];
3048 PointerProperties splitPointerProperties[MAX_POINTERS];
3049 PointerCoords splitPointerCoords[MAX_POINTERS];
3050
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003051 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 uint32_t splitPointerCount = 0;
3053
3054 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003057 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 uint32_t pointerId = uint32_t(pointerProperties.id);
3059 if (pointerIds.hasBit(pointerId)) {
3060 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3061 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3062 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003063 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 splitPointerCount += 1;
3065 }
3066 }
3067
3068 if (splitPointerCount != pointerIds.count()) {
3069 // This is bad. We are missing some of the pointers that we expected to deliver.
3070 // Most likely this indicates that we received an ACTION_MOVE events that has
3071 // different pointer ids than we expected based on the previous ACTION_DOWN
3072 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3073 // in this way.
3074 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 "we expected there to be %d pointers. This probably means we received "
3076 "a broken sequence of pointer ids from the input device.",
3077 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003078 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 }
3080
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003081 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3084 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3086 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 uint32_t pointerId = uint32_t(pointerProperties.id);
3089 if (pointerIds.hasBit(pointerId)) {
3090 if (pointerIds.count() == 1) {
3091 // The first/last pointer went down/up.
3092 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 ? AMOTION_EVENT_ACTION_DOWN
3094 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 } else {
3096 // A secondary pointer went down/up.
3097 uint32_t splitPointerIndex = 0;
3098 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3099 splitPointerIndex += 1;
3100 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 action = maskedAction |
3102 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104 } else {
3105 // An unrelated pointer changed.
3106 action = AMOTION_EVENT_ACTION_MOVE;
3107 }
3108 }
3109
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003110 int32_t newId = mIdGenerator.nextId();
3111 if (ATRACE_ENABLED()) {
3112 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3113 ") to MotionEvent(id=0x%" PRIx32 ").",
3114 originalMotionEntry.id, newId);
3115 ATRACE_NAME(message.c_str());
3116 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003117 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003118 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3119 originalMotionEntry.source, originalMotionEntry.displayId,
3120 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003121 originalMotionEntry.actionButton, originalMotionEntry.flags,
3122 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3123 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3124 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3125 originalMotionEntry.xCursorPosition,
3126 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003127 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003129 if (originalMotionEntry.injectionState) {
3130 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 splitMotionEntry->injectionState->refCount += 1;
3132 }
3133
3134 return splitMotionEntry;
3135}
3136
3137void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3138#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003139 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140#endif
3141
3142 bool needWake;
3143 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003144 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145
Prabir Pradhan42611e02018-11-27 14:04:02 -08003146 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003147 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 needWake = enqueueInboundEventLocked(newEntry);
3149 } // release lock
3150
3151 if (needWake) {
3152 mLooper->wake();
3153 }
3154}
3155
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003156/**
3157 * If one of the meta shortcuts is detected, process them here:
3158 * Meta + Backspace -> generate BACK
3159 * Meta + Enter -> generate HOME
3160 * This will potentially overwrite keyCode and metaState.
3161 */
3162void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003164 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3165 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3166 if (keyCode == AKEYCODE_DEL) {
3167 newKeyCode = AKEYCODE_BACK;
3168 } else if (keyCode == AKEYCODE_ENTER) {
3169 newKeyCode = AKEYCODE_HOME;
3170 }
3171 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003172 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003173 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003174 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003175 keyCode = newKeyCode;
3176 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3177 }
3178 } else if (action == AKEY_EVENT_ACTION_UP) {
3179 // In order to maintain a consistent stream of up and down events, check to see if the key
3180 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3181 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003182 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003183 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003184 auto replacementIt = mReplacedKeys.find(replacement);
3185 if (replacementIt != mReplacedKeys.end()) {
3186 keyCode = replacementIt->second;
3187 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003188 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3189 }
3190 }
3191}
3192
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3194#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3196 "policyFlags=0x%x, action=0x%x, "
3197 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3198 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3199 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3200 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201#endif
3202 if (!validateKeyEvent(args->action)) {
3203 return;
3204 }
3205
3206 uint32_t policyFlags = args->policyFlags;
3207 int32_t flags = args->flags;
3208 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003209 // InputDispatcher tracks and generates key repeats on behalf of
3210 // whatever notifies it, so repeatCount should always be set to 0
3211 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3213 policyFlags |= POLICY_FLAG_VIRTUAL;
3214 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 if (policyFlags & POLICY_FLAG_FUNCTION) {
3217 metaState |= AMETA_FUNCTION_ON;
3218 }
3219
3220 policyFlags |= POLICY_FLAG_TRUSTED;
3221
Michael Wright78f24442014-08-06 15:55:28 -07003222 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003223 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003224
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003226 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003227 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3228 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229
Michael Wright2b3c3302018-03-02 17:19:13 +00003230 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003232 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3233 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 bool needWake;
3238 { // acquire lock
3239 mLock.lock();
3240
3241 if (shouldSendKeyToInputFilterLocked(args)) {
3242 mLock.unlock();
3243
3244 policyFlags |= POLICY_FLAG_FILTERED;
3245 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3246 return; // event was consumed by the filter
3247 }
3248
3249 mLock.lock();
3250 }
3251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003253 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 args->displayId, policyFlags, args->action, flags, keyCode,
3255 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256
3257 needWake = enqueueInboundEventLocked(newEntry);
3258 mLock.unlock();
3259 } // release lock
3260
3261 if (needWake) {
3262 mLooper->wake();
3263 }
3264}
3265
3266bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3267 return mInputFilterEnabled;
3268}
3269
3270void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3271#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003272 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3273 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003274 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3275 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003276 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003277 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3278 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3279 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3280 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 for (uint32_t i = 0; i < args->pointerCount; i++) {
3282 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 "x=%f, y=%f, pressure=%f, size=%f, "
3284 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3285 "orientation=%f",
3286 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3287 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3288 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3289 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3290 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3291 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3292 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3293 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3294 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3295 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3299 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 return;
3301 }
3302
3303 uint32_t policyFlags = args->policyFlags;
3304 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003305
3306 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003307 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003308 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3309 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
3313 bool needWake;
3314 { // acquire lock
3315 mLock.lock();
3316
3317 if (shouldSendMotionToInputFilterLocked(args)) {
3318 mLock.unlock();
3319
3320 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003321 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003322 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3323 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003324 args->metaState, args->buttonState, args->classification, transform,
3325 args->xPrecision, args->yPrecision, args->xCursorPosition,
3326 args->yCursorPosition, args->downTime, args->eventTime,
3327 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
3329 policyFlags |= POLICY_FLAG_FILTERED;
3330 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3331 return; // event was consumed by the filter
3332 }
3333
3334 mLock.lock();
3335 }
3336
3337 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003338 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003339 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003340 args->displayId, policyFlags, args->action, args->actionButton,
3341 args->flags, args->metaState, args->buttonState,
3342 args->classification, args->edgeFlags, args->xPrecision,
3343 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3344 args->downTime, args->pointerCount, args->pointerProperties,
3345 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
3347 needWake = enqueueInboundEventLocked(newEntry);
3348 mLock.unlock();
3349 } // release lock
3350
3351 if (needWake) {
3352 mLooper->wake();
3353 }
3354}
3355
3356bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003357 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358}
3359
3360void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3361#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003362 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 "switchMask=0x%08x",
3364 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365#endif
3366
3367 uint32_t policyFlags = args->policyFlags;
3368 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370}
3371
3372void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3373#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3375 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376#endif
3377
3378 bool needWake;
3379 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003380 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
Prabir Pradhan42611e02018-11-27 14:04:02 -08003382 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003383 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 needWake = enqueueInboundEventLocked(newEntry);
3385 } // release lock
3386
3387 if (needWake) {
3388 mLooper->wake();
3389 }
3390}
3391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3393 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003394 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395#if DEBUG_INBOUND_EVENT_DETAILS
3396 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003397 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3398 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003400 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
3402 policyFlags |= POLICY_FLAG_INJECTED;
3403 if (hasInjectionPermission(injectorPid, injectorUid)) {
3404 policyFlags |= POLICY_FLAG_TRUSTED;
3405 }
3406
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003407 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003410 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3411 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 if (!validateKeyEvent(action)) {
3413 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003416 int32_t flags = incomingKey.getFlags();
3417 int32_t keyCode = incomingKey.getKeyCode();
3418 int32_t metaState = incomingKey.getMetaState();
3419 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003421 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003422 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003423 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3424 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3425 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3428 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003429 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003430
3431 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3432 android::base::Timer t;
3433 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3434 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3435 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3436 std::to_string(t.duration().count()).c_str());
3437 }
3438 }
3439
3440 mLock.lock();
3441 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003442 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3443 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003444 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3445 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003446 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 injectedEntries.push(injectedEntry);
3448 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 case AINPUT_EVENT_TYPE_MOTION: {
3452 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3453 int32_t action = motionEvent->getAction();
3454 size_t pointerCount = motionEvent->getPointerCount();
3455 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3456 int32_t actionButton = motionEvent->getActionButton();
3457 int32_t displayId = motionEvent->getDisplayId();
3458 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3459 return INPUT_EVENT_INJECTION_FAILED;
3460 }
3461
3462 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3463 nsecs_t eventTime = motionEvent->getEventTime();
3464 android::base::Timer t;
3465 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3466 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3467 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3468 std::to_string(t.duration().count()).c_str());
3469 }
3470 }
3471
3472 mLock.lock();
3473 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3474 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3475 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003476 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3477 motionEvent->getSource(), motionEvent->getDisplayId(),
3478 policyFlags, action, actionButton, motionEvent->getFlags(),
3479 motionEvent->getMetaState(), motionEvent->getButtonState(),
3480 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3481 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003482 motionEvent->getRawXCursorPosition(),
3483 motionEvent->getRawYCursorPosition(),
3484 motionEvent->getDownTime(), uint32_t(pointerCount),
3485 pointerProperties, samplePointerCoords,
3486 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487 injectedEntries.push(injectedEntry);
3488 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3489 sampleEventTimes += 1;
3490 samplePointerCoords += pointerCount;
3491 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003492 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003493 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003494 motionEvent->getDisplayId(), policyFlags, action,
3495 actionButton, motionEvent->getFlags(),
3496 motionEvent->getMetaState(), motionEvent->getButtonState(),
3497 motionEvent->getClassification(),
3498 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3499 motionEvent->getYPrecision(),
3500 motionEvent->getRawXCursorPosition(),
3501 motionEvent->getRawYCursorPosition(),
3502 motionEvent->getDownTime(), uint32_t(pointerCount),
3503 pointerProperties, samplePointerCoords,
3504 motionEvent->getXOffset(), motionEvent->getYOffset());
3505 injectedEntries.push(nextInjectedEntry);
3506 }
3507 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003511 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514
3515 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3516 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3517 injectionState->injectionIsAsync = true;
3518 }
3519
3520 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003521 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
3523 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003524 while (!injectedEntries.empty()) {
3525 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3526 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528
3529 mLock.unlock();
3530
3531 if (needWake) {
3532 mLooper->wake();
3533 }
3534
3535 int32_t injectionResult;
3536 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538
3539 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3540 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3541 } else {
3542 for (;;) {
3543 injectionResult = injectionState->injectionResult;
3544 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3545 break;
3546 }
3547
3548 nsecs_t remainingTimeout = endTime - now();
3549 if (remainingTimeout <= 0) {
3550#if DEBUG_INJECTION
3551 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003552 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553#endif
3554 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3555 break;
3556 }
3557
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003558 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3562 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 while (injectionState->pendingForegroundDispatches != 0) {
3564#if DEBUG_INJECTION
3565 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003566 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567#endif
3568 nsecs_t remainingTimeout = endTime - now();
3569 if (remainingTimeout <= 0) {
3570#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3572 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573#endif
3574 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3575 break;
3576 }
3577
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003578 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580 }
3581 }
3582
3583 injectionState->release();
3584 } // release lock
3585
3586#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003587 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589#endif
3590
3591 return injectionResult;
3592}
3593
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003594std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003595 std::array<uint8_t, 32> calculatedHmac;
3596 std::unique_ptr<VerifiedInputEvent> result;
3597 switch (event.getType()) {
3598 case AINPUT_EVENT_TYPE_KEY: {
3599 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3600 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3601 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003602 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003603 break;
3604 }
3605 case AINPUT_EVENT_TYPE_MOTION: {
3606 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3607 VerifiedMotionEvent verifiedMotionEvent =
3608 verifiedMotionEventFromMotionEvent(motionEvent);
3609 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003610 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003611 break;
3612 }
3613 default: {
3614 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3615 return nullptr;
3616 }
3617 }
3618 if (calculatedHmac == INVALID_HMAC) {
3619 return nullptr;
3620 }
3621 if (calculatedHmac != event.getHmac()) {
3622 return nullptr;
3623 }
3624 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003625}
3626
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003628 return injectorUid == 0 ||
3629 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630}
3631
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003632void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 InjectionState* injectionState = entry->injectionState;
3634 if (injectionState) {
3635#if DEBUG_INJECTION
3636 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 "injectorPid=%d, injectorUid=%d",
3638 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639#endif
3640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003641 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 // Log the outcome since the injector did not wait for the injection result.
3643 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003644 case INPUT_EVENT_INJECTION_SUCCEEDED:
3645 ALOGV("Asynchronous input event injection succeeded.");
3646 break;
3647 case INPUT_EVENT_INJECTION_FAILED:
3648 ALOGW("Asynchronous input event injection failed.");
3649 break;
3650 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3651 ALOGW("Asynchronous input event injection permission denied.");
3652 break;
3653 case INPUT_EVENT_INJECTION_TIMED_OUT:
3654 ALOGW("Asynchronous input event injection timed out.");
3655 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 }
3657 }
3658
3659 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003660 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662}
3663
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003664void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 InjectionState* injectionState = entry->injectionState;
3666 if (injectionState) {
3667 injectionState->pendingForegroundDispatches += 1;
3668 }
3669}
3670
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003671void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 InjectionState* injectionState = entry->injectionState;
3673 if (injectionState) {
3674 injectionState->pendingForegroundDispatches -= 1;
3675
3676 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003677 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
3679 }
3680}
3681
Vishnu Nairad321cd2020-08-20 16:40:21 -07003682const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003683 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003684 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3685 auto it = mWindowHandlesByDisplay.find(displayId);
3686 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003687}
3688
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003690 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003691 if (windowHandleToken == nullptr) {
3692 return nullptr;
3693 }
3694
Arthur Hungb92218b2018-08-14 12:00:21 +08003695 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003696 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003697 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003698 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003699 return windowHandle;
3700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003703 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704}
3705
Vishnu Nairad321cd2020-08-20 16:40:21 -07003706sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3707 int displayId) const {
3708 if (windowHandleToken == nullptr) {
3709 return nullptr;
3710 }
3711
3712 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3713 if (windowHandle->getToken() == windowHandleToken) {
3714 return windowHandle;
3715 }
3716 }
3717 return nullptr;
3718}
3719
3720sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3721 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3722 return getWindowHandleLocked(focusedToken, displayId);
3723}
3724
Mady Mellor017bcd12020-06-23 19:12:00 +00003725bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3726 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003727 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003728 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003729 if (handle->getId() == windowHandle->getId() &&
3730 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003731 if (windowHandle->getInfo()->displayId != it.first) {
3732 ALOGE("Found window %s in display %" PRId32
3733 ", but it should belong to display %" PRId32,
3734 windowHandle->getName().c_str(), it.first,
3735 windowHandle->getInfo()->displayId);
3736 }
3737 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 }
3740 }
3741 return false;
3742}
3743
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003744bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3745 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3746 const bool noInputChannel =
3747 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3748 if (connection != nullptr && noInputChannel) {
3749 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3750 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3751 return false;
3752 }
3753
3754 if (connection == nullptr) {
3755 if (!noInputChannel) {
3756 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3757 }
3758 return false;
3759 }
3760 if (!connection->responsive) {
3761 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3762 return false;
3763 }
3764 return true;
3765}
3766
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003767std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3768 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003769 size_t count = mInputChannelsByToken.count(token);
3770 if (count == 0) {
3771 return nullptr;
3772 }
3773 return mInputChannelsByToken.at(token);
3774}
3775
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003776void InputDispatcher::updateWindowHandlesForDisplayLocked(
3777 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3778 if (inputWindowHandles.empty()) {
3779 // Remove all handles on a display if there are no windows left.
3780 mWindowHandlesByDisplay.erase(displayId);
3781 return;
3782 }
3783
3784 // Since we compare the pointer of input window handles across window updates, we need
3785 // to make sure the handle object for the same window stays unchanged across updates.
3786 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003787 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003788 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003789 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003790 }
3791
3792 std::vector<sp<InputWindowHandle>> newHandles;
3793 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3794 if (!handle->updateInfo()) {
3795 // handle no longer valid
3796 continue;
3797 }
3798
3799 const InputWindowInfo* info = handle->getInfo();
3800 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3801 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3802 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003803 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3804 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3805 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003806 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003807 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003808 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003809 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003810 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003811 }
3812
3813 if (info->displayId != displayId) {
3814 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3815 handle->getName().c_str(), displayId, info->displayId);
3816 continue;
3817 }
3818
Robert Carredd13602020-04-13 17:24:34 -07003819 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3820 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003821 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003822 oldHandle->updateFrom(handle);
3823 newHandles.push_back(oldHandle);
3824 } else {
3825 newHandles.push_back(handle);
3826 }
3827 }
3828
3829 // Insert or replace
3830 mWindowHandlesByDisplay[displayId] = newHandles;
3831}
3832
Arthur Hung72d8dc32020-03-28 00:48:39 +00003833void InputDispatcher::setInputWindows(
3834 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3835 { // acquire lock
3836 std::scoped_lock _l(mLock);
3837 for (auto const& i : handlesPerDisplay) {
3838 setInputWindowsLocked(i.second, i.first);
3839 }
3840 }
3841 // Wake up poll loop since it may need to make new input dispatching choices.
3842 mLooper->wake();
3843}
3844
Arthur Hungb92218b2018-08-14 12:00:21 +08003845/**
3846 * Called from InputManagerService, update window handle list by displayId that can receive input.
3847 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3848 * If set an empty list, remove all handles from the specific display.
3849 * For focused handle, check if need to change and send a cancel event to previous one.
3850 * For removed handle, check if need to send a cancel event if already in touch.
3851 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003852void InputDispatcher::setInputWindowsLocked(
3853 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003854 if (DEBUG_FOCUS) {
3855 std::string windowList;
3856 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3857 windowList += iwh->getName() + " ";
3858 }
3859 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003862 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3863 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3864 const bool noInputWindow =
3865 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3866 if (noInputWindow && window->getToken() != nullptr) {
3867 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3868 window->getName().c_str());
3869 window->releaseChannel();
3870 }
3871 }
3872
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 // Copy old handles for release if they are no longer present.
3874 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Arthur Hung72d8dc32020-03-28 00:48:39 +00003876 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003877
Vishnu Nair958da932020-08-21 17:12:37 -07003878 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3879 if (mLastHoverWindowHandle &&
3880 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3881 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003882 mLastHoverWindowHandle = nullptr;
3883 }
3884
Vishnu Nair958da932020-08-21 17:12:37 -07003885 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3886 if (focusedToken) {
3887 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3888 if (result != FocusResult::OK) {
3889 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3890 }
3891 }
3892
3893 std::optional<FocusRequest> focusRequest =
3894 getOptionalValueByKey(mPendingFocusRequests, displayId);
3895 if (focusRequest) {
3896 // If the window from the pending request is now visible, provide it focus.
3897 FocusResult result = handleFocusRequestLocked(*focusRequest);
3898 if (result != FocusResult::NOT_VISIBLE) {
3899 // Drop the request if we were able to change the focus or we cannot change
3900 // it for another reason.
3901 mPendingFocusRequests.erase(displayId);
3902 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003905 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3906 mTouchStatesByDisplay.find(displayId);
3907 if (stateIt != mTouchStatesByDisplay.end()) {
3908 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003909 for (size_t i = 0; i < state.windows.size();) {
3910 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003911 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003912 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003913 ALOGD("Touched window was removed: %s in display %" PRId32,
3914 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003915 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003916 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003917 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3918 if (touchedInputChannel != nullptr) {
3919 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3920 "touched window was removed");
3921 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003923 state.windows.erase(state.windows.begin() + i);
3924 } else {
3925 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 }
3927 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003928 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003929
Arthur Hung72d8dc32020-03-28 00:48:39 +00003930 // Release information for windows that are no longer present.
3931 // This ensures that unused input channels are released promptly.
3932 // Otherwise, they might stick around until the window handle is destroyed
3933 // which might not happen until the next GC.
3934 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003935 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003936 if (DEBUG_FOCUS) {
3937 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003938 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003939 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003940 }
chaviw291d88a2019-02-14 10:33:58 -08003941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942}
3943
3944void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003945 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003946 if (DEBUG_FOCUS) {
3947 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3948 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3949 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
Chris Yea209fde2020-07-22 13:54:51 -07003953 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003954 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003955
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003956 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
3957 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003958 }
3959
Chris Yea209fde2020-07-22 13:54:51 -07003960 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003961 if (inputApplicationHandle != nullptr) {
3962 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3963 } else {
3964 mFocusedApplicationHandlesByDisplay.erase(displayId);
3965 }
3966
3967 // No matter what the old focused application was, stop waiting on it because it is
3968 // no longer focused.
3969 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 } // release lock
3971
3972 // Wake up poll loop since it may need to make new input dispatching choices.
3973 mLooper->wake();
3974}
3975
Tiger Huang721e26f2018-07-24 22:26:19 +08003976/**
3977 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3978 * the display not specified.
3979 *
3980 * We track any unreleased events for each window. If a window loses the ability to receive the
3981 * released event, we will send a cancel event to it. So when the focused display is changed, we
3982 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3983 * display. The display-specified events won't be affected.
3984 */
3985void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003986 if (DEBUG_FOCUS) {
3987 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3988 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003989 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003990 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003991
3992 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003993 sp<IBinder> oldFocusedWindowToken =
3994 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3995 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003996 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003997 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003998 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003999 CancelationOptions
4000 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4001 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004002 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004003 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4004 }
4005 }
4006 mFocusedDisplayId = displayId;
4007
Chris Ye3c2d6f52020-08-09 10:39:48 -07004008 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004009 sp<IBinder> newFocusedWindowToken =
4010 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4011 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004012
Vishnu Nairad321cd2020-08-20 16:40:21 -07004013 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004014 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004015 if (!mFocusedWindowTokenByDisplay.empty()) {
4016 ALOGE("But another display has a focused window\n%s",
4017 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004018 }
4019 }
4020 }
4021
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004022 if (DEBUG_FOCUS) {
4023 logDispatchStateLocked();
4024 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004025 } // release lock
4026
4027 // Wake up poll loop since it may need to make new input dispatching choices.
4028 mLooper->wake();
4029}
4030
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004032 if (DEBUG_FOCUS) {
4033 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
4036 bool changed;
4037 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004038 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039
4040 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4041 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004042 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 }
4044
4045 if (mDispatchEnabled && !enabled) {
4046 resetAndDropEverythingLocked("dispatcher is being disabled");
4047 }
4048
4049 mDispatchEnabled = enabled;
4050 mDispatchFrozen = frozen;
4051 changed = true;
4052 } else {
4053 changed = false;
4054 }
4055
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004056 if (DEBUG_FOCUS) {
4057 logDispatchStateLocked();
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 } // release lock
4060
4061 if (changed) {
4062 // Wake up poll loop since it may need to make new input dispatching choices.
4063 mLooper->wake();
4064 }
4065}
4066
4067void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004068 if (DEBUG_FOCUS) {
4069 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
4072 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004073 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
4075 if (mInputFilterEnabled == enabled) {
4076 return;
4077 }
4078
4079 mInputFilterEnabled = enabled;
4080 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4081 } // release lock
4082
4083 // Wake up poll loop since there might be work to do to drop everything.
4084 mLooper->wake();
4085}
4086
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004087void InputDispatcher::setInTouchMode(bool inTouchMode) {
4088 std::scoped_lock lock(mLock);
4089 mInTouchMode = inTouchMode;
4090}
4091
chaviwfbe5d9c2018-12-26 12:23:37 -08004092bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4093 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004094 if (DEBUG_FOCUS) {
4095 ALOGD("Trivial transfer to same window.");
4096 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004097 return true;
4098 }
4099
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004101 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102
chaviwfbe5d9c2018-12-26 12:23:37 -08004103 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4104 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004105 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004106 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 return false;
4108 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004109 if (DEBUG_FOCUS) {
4110 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4111 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004114 if (DEBUG_FOCUS) {
4115 ALOGD("Cannot transfer focus because windows are on different displays.");
4116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 return false;
4118 }
4119
4120 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004121 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4122 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004123 for (size_t i = 0; i < state.windows.size(); i++) {
4124 const TouchedWindow& touchedWindow = state.windows[i];
4125 if (touchedWindow.windowHandle == fromWindowHandle) {
4126 int32_t oldTargetFlags = touchedWindow.targetFlags;
4127 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004129 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 int32_t newTargetFlags = oldTargetFlags &
4132 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4133 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004134 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135
Jeff Brownf086ddb2014-02-11 14:28:48 -08004136 found = true;
4137 goto Found;
4138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
4140 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004144 if (DEBUG_FOCUS) {
4145 ALOGD("Focus transfer failed because from window did not have focus.");
4146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 return false;
4148 }
4149
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004150 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4151 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004152 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004153 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 CancelationOptions
4155 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4156 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004158 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
4160
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004161 if (DEBUG_FOCUS) {
4162 logDispatchStateLocked();
4163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 } // release lock
4165
4166 // Wake up poll loop since it may need to make new input dispatching choices.
4167 mLooper->wake();
4168 return true;
4169}
4170
4171void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004172 if (DEBUG_FOCUS) {
4173 ALOGD("Resetting and dropping all events (%s).", reason);
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
4176 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4177 synthesizeCancelationEventsForAllConnectionsLocked(options);
4178
4179 resetKeyRepeatLocked();
4180 releasePendingEventLocked();
4181 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004182 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004184 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004185 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004187 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188}
4189
4190void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 dumpDispatchStateLocked(dump);
4193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 std::istringstream stream(dump);
4195 std::string line;
4196
4197 while (std::getline(stream, line, '\n')) {
4198 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 }
4200}
4201
Vishnu Nairad321cd2020-08-20 16:40:21 -07004202std::string InputDispatcher::dumpFocusedWindowsLocked() {
4203 if (mFocusedWindowTokenByDisplay.empty()) {
4204 return INDENT "FocusedWindows: <none>\n";
4205 }
4206
4207 std::string dump;
4208 dump += INDENT "FocusedWindows:\n";
4209 for (auto& it : mFocusedWindowTokenByDisplay) {
4210 const int32_t displayId = it.first;
4211 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4212 if (windowHandle) {
4213 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4214 windowHandle->getName().c_str());
4215 } else {
4216 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4217 " has focused token without a window'\n",
4218 displayId);
4219 }
4220 }
4221 return dump;
4222}
4223
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004225 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4226 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4227 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004228 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229
Tiger Huang721e26f2018-07-24 22:26:19 +08004230 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4231 dump += StringPrintf(INDENT "FocusedApplications:\n");
4232 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4233 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004234 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004235 const std::chrono::duration timeout =
4236 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004238 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004239 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004242 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004244
Vishnu Nairad321cd2020-08-20 16:40:21 -07004245 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004247 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004248 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004249 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4250 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 state.displayId, toString(state.down), toString(state.split),
4253 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004254 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004256 for (size_t i = 0; i < state.windows.size(); i++) {
4257 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 dump += StringPrintf(INDENT4
4259 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4260 i, touchedWindow.windowHandle->getName().c_str(),
4261 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004262 }
4263 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004265 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004266 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004267 dump += INDENT3 "Portal windows:\n";
4268 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004269 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4271 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004272 }
4273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 }
4275 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004276 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
Arthur Hungb92218b2018-08-14 12:00:21 +08004279 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004281 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004282 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004283 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004284 dump += INDENT2 "Windows:\n";
4285 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004286 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004287 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Arthur Hungb92218b2018-08-14 12:00:21 +08004289 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004290 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4291 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004292 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004294 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004295 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 i, windowInfo->name.c_str(), windowInfo->displayId,
4297 windowInfo->portalToDisplayId,
4298 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004299 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 toString(windowInfo->hasWallpaper),
4301 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004302 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004303 static_cast<int32_t>(windowInfo->type),
4304 windowInfo->frameLeft, windowInfo->frameTop,
4305 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004306 windowInfo->globalScaleFactor,
4307 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004308 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004309 dump += StringPrintf(", inputFeatures=%s",
4310 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004311 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4312 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004313 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004314 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004315 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004316 }
4317 } else {
4318 dump += INDENT2 "Windows: <none>\n";
4319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
4321 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004322 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324
Michael Wright3dd60e22019-03-27 22:06:44 +00004325 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004326 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004327 const std::vector<Monitor>& monitors = it.second;
4328 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4329 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 }
4331 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004332 const std::vector<Monitor>& monitors = it.second;
4333 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4334 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004337 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339
4340 nsecs_t currentTime = now();
4341
4342 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004343 if (!mRecentQueue.empty()) {
4344 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4345 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004348 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
4350 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353
4354 // Dump event currently being dispatched.
4355 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004356 dump += INDENT "PendingEvent:\n";
4357 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004359 dump += StringPrintf(", age=%" PRId64 "ms\n",
4360 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004362 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 }
4364
4365 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004366 if (!mInboundQueue.empty()) {
4367 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4368 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004371 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 }
4373 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 }
4376
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004377 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004378 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004379 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4380 const KeyReplacement& replacement = pair.first;
4381 int32_t newKeyCode = pair.second;
4382 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004384 }
4385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004386 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004387 }
4388
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004389 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004391 for (const auto& pair : mConnectionsByFd) {
4392 const sp<Connection>& connection = pair.second;
4393 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004395 pair.first, connection->getInputChannelName().c_str(),
4396 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004397 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004399 if (!connection->outboundQueue.empty()) {
4400 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4401 connection->outboundQueue.size());
4402 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 dump.append(INDENT4);
4404 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4406 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004408 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 }
4410 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004411 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
4413
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004414 if (!connection->waitQueue.empty()) {
4415 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4416 connection->waitQueue.size());
4417 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004418 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004420 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004421 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004423 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004424 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 }
4426 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004427 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 }
4429 }
4430 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004431 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 }
4433
4434 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004435 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4436 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004438 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
4440
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004441 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004442 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4443 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4444 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445}
4446
Michael Wright3dd60e22019-03-27 22:06:44 +00004447void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4448 const size_t numMonitors = monitors.size();
4449 for (size_t i = 0; i < numMonitors; i++) {
4450 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004451 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4453 dump += "\n";
4454 }
4455}
4456
Garfield Tan15601662020-09-22 15:32:38 -07004457base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4458 const std::string& name) {
4459#if DEBUG_CHANNEL_CREATION
4460 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461#endif
4462
Garfield Tan15601662020-09-22 15:32:38 -07004463 std::shared_ptr<InputChannel> serverChannel;
4464 std::unique_ptr<InputChannel> clientChannel;
4465 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4466
4467 if (result) {
4468 return base::Error(result) << "Failed to open input channel pair with name " << name;
4469 }
4470
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004472 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004473 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474
Garfield Tan15601662020-09-22 15:32:38 -07004475 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004476 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004477 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4480 } // release lock
4481
4482 // Wake the looper because some connections have changed.
4483 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004484 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485}
4486
Garfield Tan15601662020-09-22 15:32:38 -07004487base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4488 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4489 std::shared_ptr<InputChannel> serverChannel;
4490 std::unique_ptr<InputChannel> clientChannel;
4491 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4492 if (result) {
4493 return base::Error(result) << "Failed to open input channel pair with name " << name;
4494 }
4495
Michael Wright3dd60e22019-03-27 22:06:44 +00004496 { // acquire lock
4497 std::scoped_lock _l(mLock);
4498
4499 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004500 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4501 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004502 }
4503
Garfield Tan15601662020-09-22 15:32:38 -07004504 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004505
Garfield Tan15601662020-09-22 15:32:38 -07004506 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004507 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004508 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004509
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004510 auto& monitorsByDisplay =
4511 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004512 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004513
4514 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004515 }
Garfield Tan15601662020-09-22 15:32:38 -07004516
Michael Wright3dd60e22019-03-27 22:06:44 +00004517 // Wake the looper because some connections have changed.
4518 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004519 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004520}
4521
Garfield Tan15601662020-09-22 15:32:38 -07004522status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004524 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
Garfield Tan15601662020-09-22 15:32:38 -07004526 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 if (status) {
4528 return status;
4529 }
4530 } // release lock
4531
4532 // Wake the poll loop because removing the connection may have changed the current
4533 // synchronization state.
4534 mLooper->wake();
4535 return OK;
4536}
4537
Garfield Tan15601662020-09-22 15:32:38 -07004538status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4539 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004540 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004541 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004542 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 return BAD_VALUE;
4544 }
4545
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004546 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004547 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004548
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004550 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 }
4552
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004553 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
4555 nsecs_t currentTime = now();
4556 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4557
4558 connection->status = Connection::STATUS_ZOMBIE;
4559 return OK;
4560}
4561
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004562void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4563 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4564 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004565}
4566
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004567void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004568 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004569 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004571 std::vector<Monitor>& monitors = it->second;
4572 const size_t numMonitors = monitors.size();
4573 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004574 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 monitors.erase(monitors.begin() + i);
4576 break;
4577 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004578 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004579 if (monitors.empty()) {
4580 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004581 } else {
4582 ++it;
4583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 }
4585}
4586
Michael Wright3dd60e22019-03-27 22:06:44 +00004587status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4588 { // acquire lock
4589 std::scoped_lock _l(mLock);
4590 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4591
4592 if (!foundDisplayId) {
4593 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4594 return BAD_VALUE;
4595 }
4596 int32_t displayId = foundDisplayId.value();
4597
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004598 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4599 mTouchStatesByDisplay.find(displayId);
4600 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004601 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4602 return BAD_VALUE;
4603 }
4604
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004605 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004606 std::optional<int32_t> foundDeviceId;
4607 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004608 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004609 foundDeviceId = state.deviceId;
4610 }
4611 }
4612 if (!foundDeviceId || !state.down) {
4613 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004615 return BAD_VALUE;
4616 }
4617 int32_t deviceId = foundDeviceId.value();
4618
4619 // Send cancel events to all the input channels we're stealing from.
4620 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004622 options.deviceId = deviceId;
4623 options.displayId = displayId;
4624 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004625 std::shared_ptr<InputChannel> channel =
4626 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004627 if (channel != nullptr) {
4628 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4629 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004630 }
4631 // Then clear the current touch state so we stop dispatching to them as well.
4632 state.filterNonMonitors();
4633 }
4634 return OK;
4635}
4636
Michael Wright3dd60e22019-03-27 22:06:44 +00004637std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4638 const sp<IBinder>& token) {
4639 for (const auto& it : mGestureMonitorsByDisplay) {
4640 const std::vector<Monitor>& monitors = it.second;
4641 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004642 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004643 return it.first;
4644 }
4645 }
4646 }
4647 return std::nullopt;
4648}
4649
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004650sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004651 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004652 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004653 }
4654
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004655 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004656 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004657 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004658 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 }
4660 }
Robert Carr4e670e52018-08-15 13:26:12 -07004661
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004662 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663}
4664
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004665void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004666 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004667 removeByValue(mConnectionsByFd, connection);
4668}
4669
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004670void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4671 const sp<Connection>& connection, uint32_t seq,
4672 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004673 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4674 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 commandEntry->connection = connection;
4676 commandEntry->eventTime = currentTime;
4677 commandEntry->seq = seq;
4678 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004679 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680}
4681
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004682void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4683 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004687 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4688 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004690 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
Vishnu Nairad321cd2020-08-20 16:40:21 -07004693void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4694 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004695 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4696 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004697 commandEntry->oldToken = oldToken;
4698 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004699 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004700}
4701
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004702void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4704 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004705 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004706 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004707 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004708 return;
4709 }
4710 /**
4711 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4712 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4713 * has changed. This could cause newer entries to time out before the already dispatched
4714 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4715 * processes the events linearly. So providing information about the oldest entry seems to be
4716 * most useful.
4717 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004718 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004719 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4720 std::string reason =
4721 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004722 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004723 ns2ms(currentWait),
4724 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004726 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 reason);
4728
4729 std::unique_ptr<CommandEntry> commandEntry =
4730 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4731 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004732 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 commandEntry->reason = std::move(reason);
4734 postCommandLocked(std::move(commandEntry));
4735}
4736
Chris Yea209fde2020-07-22 13:54:51 -07004737void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4739 application->getName().c_str());
4740
4741 updateLastAnrStateLocked(application, reason);
4742
4743 std::unique_ptr<CommandEntry> commandEntry =
4744 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4745 commandEntry->inputApplicationHandle = application;
4746 commandEntry->inputChannel = nullptr;
4747 commandEntry->reason = std::move(reason);
4748 postCommandLocked(std::move(commandEntry));
4749}
4750
4751void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4752 const std::string& reason) {
4753 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4754 updateLastAnrStateLocked(windowLabel, reason);
4755}
4756
Chris Yea209fde2020-07-22 13:54:51 -07004757void InputDispatcher::updateLastAnrStateLocked(
4758 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4760 updateLastAnrStateLocked(windowLabel, reason);
4761}
4762
4763void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4764 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004766 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 struct tm tm;
4768 localtime_r(&t, &tm);
4769 char timestr[64];
4770 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004771 mLastAnrState.clear();
4772 mLastAnrState += INDENT "ANR:\n";
4773 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4775 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004776 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777}
4778
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 mLock.unlock();
4781
4782 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4783
4784 mLock.lock();
4785}
4786
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 sp<Connection> connection = commandEntry->connection;
4789
4790 if (connection->status != Connection::STATUS_ZOMBIE) {
4791 mLock.unlock();
4792
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004793 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794
4795 mLock.lock();
4796 }
4797}
4798
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004800 sp<IBinder> oldToken = commandEntry->oldToken;
4801 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004802 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004803 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004804 mLock.lock();
4805}
4806
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004807void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004808 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004809 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 mLock.unlock();
4811
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004812 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004813 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
4815 mLock.lock();
4816
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004817 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4819 } else {
4820 // stop waking up for events in this connection, it is already not responding
4821 sp<Connection> connection = getConnectionLocked(token);
4822 if (connection == nullptr) {
4823 return;
4824 }
4825 cancelEventsForAnrLocked(connection);
4826 }
4827}
4828
Chris Yea209fde2020-07-22 13:54:51 -07004829void InputDispatcher::extendAnrTimeoutsLocked(
4830 const std::shared_ptr<InputApplicationHandle>& application,
4831 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004832 if (connectionToken == nullptr && application != nullptr) {
4833 // The ANR happened because there's no focused window
4834 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4835 mAwaitedFocusedApplication = application;
4836 }
4837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 sp<Connection> connection = getConnectionLocked(connectionToken);
4839 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004840 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 return;
4842 }
4843
4844 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004845 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846
4847 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004848 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 for (DispatchEntry* entry : connection->waitQueue) {
4850 if (newTimeout >= entry->timeoutTime) {
4851 // Already removed old entries when connection was marked unresponsive
4852 entry->timeoutTime = newTimeout;
4853 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4854 }
4855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856}
4857
4858void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4859 CommandEntry* commandEntry) {
4860 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004861 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862
4863 mLock.unlock();
4864
Michael Wright2b3c3302018-03-02 17:19:13 +00004865 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004867 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004868 : nullptr;
4869 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004870 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4871 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004872 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874
4875 mLock.lock();
4876
4877 if (delay < 0) {
4878 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4879 } else if (!delay) {
4880 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4881 } else {
4882 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4883 entry->interceptKeyWakeupTime = now() + delay;
4884 }
4885 entry->release();
4886}
4887
chaviwfd6d3512019-03-25 13:23:49 -07004888void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4889 mLock.unlock();
4890 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4891 mLock.lock();
4892}
4893
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894/**
4895 * Connection is responsive if it has no events in the waitQueue that are older than the
4896 * current time.
4897 */
4898static bool isConnectionResponsive(const Connection& connection) {
4899 const nsecs_t currentTime = now();
4900 for (const DispatchEntry* entry : connection.waitQueue) {
4901 if (entry->timeoutTime < currentTime) {
4902 return false;
4903 }
4904 }
4905 return true;
4906}
4907
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004910 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004912 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
4914 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004915 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004916 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004917 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004919 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004920 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004921 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004922 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4923 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004924 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004925 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004926
4927 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004928 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004929 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4930 restartEvent =
4931 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004932 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004933 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4934 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4935 handled);
4936 } else {
4937 restartEvent = false;
4938 }
4939
4940 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004941 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004942 // contents of the wait queue to have been drained, so we need to double-check
4943 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004944 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4945 if (dispatchEntryIt != connection->waitQueue.end()) {
4946 dispatchEntry = *dispatchEntryIt;
4947 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948 mAnrTracker.erase(dispatchEntry->timeoutTime,
4949 connection->inputChannel->getConnectionToken());
4950 if (!connection->responsive) {
4951 connection->responsive = isConnectionResponsive(*connection);
4952 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004953 traceWaitQueueLength(connection);
4954 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004955 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004956 traceOutboundQueueLength(connection);
4957 } else {
4958 releaseDispatchEntry(dispatchEntry);
4959 }
4960 }
4961
4962 // Start the next dispatch cycle for this connection.
4963 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964}
4965
4966bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004967 DispatchEntry* dispatchEntry,
4968 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004970 if (!handled) {
4971 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004972 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004974 return false;
4975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004977 // Get the fallback key state.
4978 // Clear it out after dispatching the UP.
4979 int32_t originalKeyCode = keyEntry->keyCode;
4980 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4981 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4982 connection->inputState.removeFallbackKey(originalKeyCode);
4983 }
4984
4985 if (handled || !dispatchEntry->hasForegroundTarget()) {
4986 // If the application handles the original key for which we previously
4987 // generated a fallback or if the window is not a foreground window,
4988 // then cancel the associated fallback key, if any.
4989 if (fallbackKeyCode != -1) {
4990 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004992 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004993 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4994 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4995 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004997 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004998 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999
5000 mLock.unlock();
5001
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005002 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
5005 mLock.lock();
5006
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005007 // Cancel the fallback key.
5008 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005010 "application handled the original non-fallback key "
5011 "or is no longer a foreground target, "
5012 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 options.keyCode = fallbackKeyCode;
5014 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005016 connection->inputState.removeFallbackKey(originalKeyCode);
5017 }
5018 } else {
5019 // If the application did not handle a non-fallback key, first check
5020 // that we are in a good state to perform unhandled key event processing
5021 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005023 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005025 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005026 "since this is not an initial down. "
5027 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5028 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005030 return false;
5031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005033 // Dispatch the unhandled key to the policy.
5034#if DEBUG_OUTBOUND_EVENT_DETAILS
5035 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5037 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005038#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005039 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005040
5041 mLock.unlock();
5042
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005043 bool fallback =
5044 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5045 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005046
5047 mLock.lock();
5048
5049 if (connection->status != Connection::STATUS_NORMAL) {
5050 connection->inputState.removeFallbackKey(originalKeyCode);
5051 return false;
5052 }
5053
5054 // Latch the fallback keycode for this key on an initial down.
5055 // The fallback keycode cannot change at any other point in the lifecycle.
5056 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005058 fallbackKeyCode = event.getKeyCode();
5059 } else {
5060 fallbackKeyCode = AKEYCODE_UNKNOWN;
5061 }
5062 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5063 }
5064
5065 ALOG_ASSERT(fallbackKeyCode != -1);
5066
5067 // Cancel the fallback key if the policy decides not to send it anymore.
5068 // We will continue to dispatch the key to the policy but we will no
5069 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005070 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5071 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005072#if DEBUG_OUTBOUND_EVENT_DETAILS
5073 if (fallback) {
5074 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005075 "as a fallback for %d, but on the DOWN it had requested "
5076 "to send %d instead. Fallback canceled.",
5077 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005078 } else {
5079 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005080 "but on the DOWN it had requested to send %d. "
5081 "Fallback canceled.",
5082 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005083 }
5084#endif
5085
5086 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5087 "canceling fallback, policy no longer desires it");
5088 options.keyCode = fallbackKeyCode;
5089 synthesizeCancelationEventsForConnectionLocked(connection, options);
5090
5091 fallback = false;
5092 fallbackKeyCode = AKEYCODE_UNKNOWN;
5093 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005094 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005095 }
5096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097
5098#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005099 {
5100 std::string msg;
5101 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5102 connection->inputState.getFallbackKeys();
5103 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005104 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005106 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005108 }
5109#endif
5110
5111 if (fallback) {
5112 // Restart the dispatch cycle using the fallback key.
5113 keyEntry->eventTime = event.getEventTime();
5114 keyEntry->deviceId = event.getDeviceId();
5115 keyEntry->source = event.getSource();
5116 keyEntry->displayId = event.getDisplayId();
5117 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5118 keyEntry->keyCode = fallbackKeyCode;
5119 keyEntry->scanCode = event.getScanCode();
5120 keyEntry->metaState = event.getMetaState();
5121 keyEntry->repeatCount = event.getRepeatCount();
5122 keyEntry->downTime = event.getDownTime();
5123 keyEntry->syntheticRepeat = false;
5124
5125#if DEBUG_OUTBOUND_EVENT_DETAILS
5126 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005127 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5128 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005129#endif
5130 return true; // restart the event
5131 } else {
5132#if DEBUG_OUTBOUND_EVENT_DETAILS
5133 ALOGD("Unhandled key event: No fallback key.");
5134#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005135
5136 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005137 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 }
5139 }
5140 return false;
5141}
5142
5143bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005144 DispatchEntry* dispatchEntry,
5145 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 return false;
5147}
5148
5149void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5150 mLock.unlock();
5151
5152 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5153
5154 mLock.lock();
5155}
5156
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005157KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5158 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005159 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005160 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5161 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005162 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163}
5164
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005165void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5166 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 // TODO Write some statistics about how long we spend waiting.
5168}
5169
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005170/**
5171 * Report the touch event latency to the statsd server.
5172 * Input events are reported for statistics if:
5173 * - This is a touchscreen event
5174 * - InputFilter is not enabled
5175 * - Event is not injected or synthesized
5176 *
5177 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5178 * from getting aggregated with the "old" data.
5179 */
5180void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5181 REQUIRES(mLock) {
5182 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5183 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5184 if (!reportForStatistics) {
5185 return;
5186 }
5187
5188 if (mTouchStatistics.shouldReport()) {
5189 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5190 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5191 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5192 mTouchStatistics.reset();
5193 }
5194 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5195 mTouchStatistics.addValue(latencyMicros);
5196}
5197
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198void InputDispatcher::traceInboundQueueLengthLocked() {
5199 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005200 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 }
5202}
5203
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005204void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 if (ATRACE_ENABLED()) {
5206 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005207 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005208 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005209 }
5210}
5211
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005212void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 if (ATRACE_ENABLED()) {
5214 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005215 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005216 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 }
5218}
5219
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005220void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005221 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005223 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 dumpDispatchStateLocked(dump);
5225
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005226 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005227 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005228 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 }
5230}
5231
5232void InputDispatcher::monitor() {
5233 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005234 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005236 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237}
5238
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005239/**
5240 * Wake up the dispatcher and wait until it processes all events and commands.
5241 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5242 * this method can be safely called from any thread, as long as you've ensured that
5243 * the work you are interested in completing has already been queued.
5244 */
5245bool InputDispatcher::waitForIdle() {
5246 /**
5247 * Timeout should represent the longest possible time that a device might spend processing
5248 * events and commands.
5249 */
5250 constexpr std::chrono::duration TIMEOUT = 100ms;
5251 std::unique_lock lock(mLock);
5252 mLooper->wake();
5253 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5254 return result == std::cv_status::no_timeout;
5255}
5256
Vishnu Naire798b472020-07-23 13:52:21 -07005257/**
5258 * Sets focus to the window identified by the token. This must be called
5259 * after updating any input window handles.
5260 *
5261 * Params:
5262 * request.token - input channel token used to identify the window that should gain focus.
5263 * request.focusedToken - the token that the caller expects currently to be focused. If the
5264 * specified token does not match the currently focused window, this request will be dropped.
5265 * If the specified focused token matches the currently focused window, the call will succeed.
5266 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5267 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5268 * when requesting the focus change. This determines which request gets
5269 * precedence if there is a focus change request from another source such as pointer down.
5270 */
Vishnu Nair958da932020-08-21 17:12:37 -07005271void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5272 { // acquire lock
5273 std::scoped_lock _l(mLock);
5274
5275 const int32_t displayId = request.displayId;
5276 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5277 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5278 ALOGD_IF(DEBUG_FOCUS,
5279 "setFocusedWindow on display %" PRId32
5280 " ignored, reason: focusedToken is not focused",
5281 displayId);
5282 return;
5283 }
5284
5285 mPendingFocusRequests.erase(displayId);
5286 FocusResult result = handleFocusRequestLocked(request);
5287 if (result == FocusResult::NOT_VISIBLE) {
5288 // The requested window is not currently visible. Wait for the window to become visible
5289 // and then provide it focus. This is to handle situations where a user action triggers
5290 // a new window to appear. We want to be able to queue any key events after the user
5291 // action and deliver it to the newly focused window. In order for this to happen, we
5292 // take focus from the currently focused window so key events can be queued.
5293 ALOGD_IF(DEBUG_FOCUS,
5294 "setFocusedWindow on display %" PRId32
5295 " pending, reason: window is not visible",
5296 displayId);
5297 mPendingFocusRequests[displayId] = request;
5298 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5299 "setFocusedWindow_AwaitingWindowVisibility");
5300 } else if (result != FocusResult::OK) {
5301 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5302 typeToString(result));
5303 }
5304 } // release lock
5305 // Wake up poll loop since it may need to make new input dispatching choices.
5306 mLooper->wake();
5307}
5308
5309InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5310 const FocusRequest& request) {
5311 const int32_t displayId = request.displayId;
5312 const sp<IBinder> newFocusedToken = request.token;
5313 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5314
5315 if (oldFocusedToken == request.token) {
5316 ALOGD_IF(DEBUG_FOCUS,
5317 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5318 displayId);
5319 return FocusResult::OK;
5320 }
5321
5322 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5323 if (result != FocusResult::OK) {
5324 return result;
5325 }
5326
5327 std::string_view reason =
5328 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5329 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5330 return FocusResult::OK;
5331}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005332
Vishnu Nairad321cd2020-08-20 16:40:21 -07005333void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5334 const sp<IBinder>& newFocusedToken, int32_t displayId,
5335 std::string_view reason) {
5336 if (oldFocusedToken) {
5337 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005338 if (focusedInputChannel) {
5339 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5340 "focus left window");
5341 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005342 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005343 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005344 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005345 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005346 if (newFocusedToken) {
5347 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5348 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005349 }
5350
5351 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005352 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005353 }
5354}
Vishnu Nair958da932020-08-21 17:12:37 -07005355
5356/**
5357 * Checks if the window token can be focused on a display. The token can be focused if there is
5358 * at least one window handle that is visible with the same token and all window handles with the
5359 * same token are focusable.
5360 *
5361 * In the case of mirroring, two windows may share the same window token and their visibility
5362 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5363 * we expect the focusability of the windows to match since its hard to reason why one window can
5364 * receive focus events and the other cannot when both are backed by the same input channel.
5365 */
5366InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5367 int32_t displayId) const {
5368 bool allWindowsAreFocusable = true;
5369 bool visibleWindowFound = false;
5370 bool windowFound = false;
5371 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5372 if (window->getToken() != token) {
5373 continue;
5374 }
5375 windowFound = true;
5376 if (window->getInfo()->visible) {
5377 // Check if at least a single window is visible.
5378 visibleWindowFound = true;
5379 }
5380 if (!window->getInfo()->focusable) {
5381 // Check if all windows with the window token are focusable.
5382 allWindowsAreFocusable = false;
5383 break;
5384 }
5385 }
5386
5387 if (!windowFound) {
5388 return FocusResult::NO_WINDOW;
5389 }
5390 if (!allWindowsAreFocusable) {
5391 return FocusResult::NOT_FOCUSABLE;
5392 }
5393 if (!visibleWindowFound) {
5394 return FocusResult::NOT_VISIBLE;
5395 }
5396
5397 return FocusResult::OK;
5398}
Garfield Tane84e6f92019-08-29 17:28:41 -07005399} // namespace android::inputdispatcher