blob: 6460fe990c478f7f588b8d19439f11151fef640b [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
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
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
Vishnu Nair958da932020-08-21 17:12:37 -0700354const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
355 switch (result) {
356 case InputDispatcher::FocusResult::OK:
357 return "Ok";
358 case InputDispatcher::FocusResult::NO_WINDOW:
359 return "Window not found";
360 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
361 return "Window not focusable";
362 case InputDispatcher::FocusResult::NOT_VISIBLE:
363 return "Window not visible";
364 }
365}
366
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367// --- InputDispatcher ---
368
Garfield Tan00f511d2019-06-12 16:55:40 -0700369InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
370 : mPolicy(policy),
371 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700372 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800373 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700374 mAppSwitchSawKeyDown(false),
375 mAppSwitchDueTime(LONG_LONG_MAX),
376 mNextUnblockedEvent(nullptr),
377 mDispatchEnabled(false),
378 mDispatchFrozen(false),
379 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800380 // mInTouchMode will be initialized by the WindowManager to the default device config.
381 // To avoid leaking stack in case that call never comes, and for tests,
382 // initialize it here anyways.
383 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700384 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800386 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800387
Yi Kong9b14ac62018-07-17 13:48:38 -0700388 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389
390 policy->getDispatcherConfiguration(&mConfig);
391}
392
393InputDispatcher::~InputDispatcher() {
394 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800395 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396
397 resetKeyRepeatLocked();
398 releasePendingEventLocked();
399 drainInboundQueueLocked();
400 }
401
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700402 while (!mConnectionsByFd.empty()) {
403 sp<Connection> connection = mConnectionsByFd.begin()->second;
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -0500404 unregisterInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 }
406}
407
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700408status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700409 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700410 return ALREADY_EXISTS;
411 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700412 mThread = std::make_unique<InputThread>(
413 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
414 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700415}
416
417status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700418 if (mThread && mThread->isCallingThread()) {
419 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700420 return INVALID_OPERATION;
421 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700422 mThread.reset();
423 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700424}
425
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426void InputDispatcher::dispatchOnce() {
427 nsecs_t nextWakeupTime = LONG_LONG_MAX;
428 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800429 std::scoped_lock _l(mLock);
430 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431
432 // Run a dispatch loop if there are no pending commands.
433 // The dispatch loop might enqueue commands to run afterwards.
434 if (!haveCommandsLocked()) {
435 dispatchOnceInnerLocked(&nextWakeupTime);
436 }
437
438 // Run all pending commands if there are any.
439 // If any commands were run then force the next poll to wake up immediately.
440 if (runCommandsLockedInterruptible()) {
441 nextWakeupTime = LONG_LONG_MIN;
442 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800443
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700444 // If we are still waiting for ack on some events,
445 // we might have to wake up earlier to check if an app is anr'ing.
446 const nsecs_t nextAnrCheck = processAnrsLocked();
447 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
448
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800449 // We are about to enter an infinitely long sleep, because we have no commands or
450 // pending or queued events
451 if (nextWakeupTime == LONG_LONG_MAX) {
452 mDispatcherEnteredIdle.notify_all();
453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 } // release lock
455
456 // Wait for callback or timeout or wake. (make sure we round up, not down)
457 nsecs_t currentTime = now();
458 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
459 mLooper->pollOnce(timeoutMillis);
460}
461
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700462/**
463 * Check if any of the connections' wait queues have events that are too old.
464 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
465 * Return the time at which we should wake up next.
466 */
467nsecs_t InputDispatcher::processAnrsLocked() {
468 const nsecs_t currentTime = now();
469 nsecs_t nextAnrCheck = LONG_LONG_MAX;
470 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
471 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
472 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
473 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700474 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700475 return LONG_LONG_MIN;
476 } else {
477 // Keep waiting
478 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
479 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
480 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
481 }
482 }
483
484 // Check if any connection ANRs are due
485 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
486 if (currentTime < nextAnrCheck) { // most likely scenario
487 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
488 }
489
490 // If we reached here, we have an unresponsive connection.
491 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
492 if (connection == nullptr) {
493 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
494 return nextAnrCheck;
495 }
496 connection->responsive = false;
497 // Stop waking up for this unresponsive connection
498 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
499 onAnrLocked(connection);
500 return LONG_LONG_MIN;
501}
502
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500503std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700504 sp<InputWindowHandle> window = getWindowHandleLocked(token);
505 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500506 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700507 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500508 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700509}
510
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
512 nsecs_t currentTime = now();
513
Jeff Browndc5992e2014-04-11 01:27:26 -0700514 // Reset the key repeat timer whenever normal dispatch is suspended while the
515 // device is in a non-interactive state. This is to ensure that we abort a key
516 // repeat if the device is just coming out of sleep.
517 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 resetKeyRepeatLocked();
519 }
520
521 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
522 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100523 if (DEBUG_FOCUS) {
524 ALOGD("Dispatch frozen. Waiting some more.");
525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 return;
527 }
528
529 // Optimize latency of app switches.
530 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
531 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
532 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
533 if (mAppSwitchDueTime < *nextWakeupTime) {
534 *nextWakeupTime = mAppSwitchDueTime;
535 }
536
537 // Ready to start a new event.
538 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700539 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700540 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 if (isAppSwitchDue) {
542 // The inbound queue is empty so the app switch key we were waiting
543 // for will never arrive. Stop waiting for it.
544 resetPendingAppSwitchLocked(false);
545 isAppSwitchDue = false;
546 }
547
548 // Synthesize a key repeat if appropriate.
549 if (mKeyRepeatState.lastKeyEntry) {
550 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
551 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
552 } else {
553 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
554 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
555 }
556 }
557 }
558
559 // Nothing to do if there is no pending event.
560 if (!mPendingEvent) {
561 return;
562 }
563 } else {
564 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700565 mPendingEvent = mInboundQueue.front();
566 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 traceInboundQueueLengthLocked();
568 }
569
570 // Poke user activity for this event.
571 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700572 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 }
575
576 // Now we have an event to dispatch.
577 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700578 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700580 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700582 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700584 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 }
586
587 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700588 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 }
590
591 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700592 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700593 ConfigurationChangedEntry* typedEntry =
594 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
595 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700596 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 break;
598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700600 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
602 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700603 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700604 break;
605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100607 case EventEntry::Type::FOCUS: {
608 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
609 dispatchFocusLocked(currentTime, typedEntry);
610 done = true;
611 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
612 break;
613 }
614
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700615 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700616 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
617 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700618 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 resetPendingAppSwitchLocked(true);
620 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700621 } else if (dropReason == DropReason::NOT_DROPPED) {
622 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 }
624 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700625 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700626 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700627 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700628 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
629 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 }
631 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
632 break;
633 }
634
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700635 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
638 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700641 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700643 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
644 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 }
646 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
647 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 }
650
651 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700652 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700653 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 }
Michael Wright3a981722015-06-10 15:26:13 +0100655 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656
657 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 }
660}
661
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700662/**
663 * Return true if the events preceding this incoming motion event should be dropped
664 * Return false otherwise (the default behaviour)
665 */
666bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700667 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700668 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700669
670 // Optimize case where the current application is unresponsive and the user
671 // decides to touch a window in a different application.
672 // If the application takes too long to catch up then we drop all events preceding
673 // the touch into the other window.
674 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700675 int32_t displayId = motionEntry.displayId;
676 int32_t x = static_cast<int32_t>(
677 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
678 int32_t y = static_cast<int32_t>(
679 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
680 sp<InputWindowHandle> touchedWindowHandle =
681 findTouchedWindowAtLocked(displayId, x, y, nullptr);
682 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700683 touchedWindowHandle->getApplicationToken() !=
684 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700685 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686 ALOGI("Pruning input queue because user touched a different application while waiting "
687 "for %s",
688 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700689 return true;
690 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691
692 // Alternatively, maybe there's a gesture monitor that could handle this event
693 std::vector<TouchedMonitor> gestureMonitors =
694 findTouchedGestureMonitorsLocked(displayId, {});
695 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
696 sp<Connection> connection =
697 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000698 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700699 // This monitor could take more input. Drop all events preceding this
700 // event, so that gesture monitor could get a chance to receive the stream
701 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
702 "responsive gesture monitor that may handle the event",
703 mAwaitedFocusedApplication->getName().c_str());
704 return true;
705 }
706 }
707 }
708
709 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
710 // yet been processed by some connections, the dispatcher will wait for these motion
711 // events to be processed before dispatching the key event. This is because these motion events
712 // may cause a new window to be launched, which the user might expect to receive focus.
713 // To prevent waiting forever for such events, just send the key to the currently focused window
714 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
715 ALOGD("Received a new pointer down event, stop waiting for events to process and "
716 "just send the pending key event to the focused window.");
717 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700718 }
719 return false;
720}
721
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700723 bool needWake = mInboundQueue.empty();
724 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 traceInboundQueueLengthLocked();
726
727 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700728 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 // Optimize app switch latency.
730 // If the application takes too long to catch up then we drop all events preceding
731 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700732 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700734 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700736 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700739 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700741 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 mAppSwitchSawKeyDown = false;
743 needWake = true;
744 }
745 }
746 }
747 break;
748 }
749
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700750 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700751 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
752 mNextUnblockedEvent = entry;
753 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100757 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700758 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
759 break;
760 }
761 case EventEntry::Type::CONFIGURATION_CHANGED:
762 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700763 // nothing to do
764 break;
765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 }
767
768 return needWake;
769}
770
771void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
772 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700773 mRecentQueue.push_back(entry);
774 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
775 mRecentQueue.front()->release();
776 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778}
779
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700781 int32_t y, TouchState* touchState,
782 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700784 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
785 LOG_ALWAYS_FATAL(
786 "Must provide a valid touch state if adding portal windows or outside targets");
787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700789 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800790 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 const InputWindowInfo* windowInfo = windowHandle->getInfo();
792 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100793 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
795 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100796 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
797 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
798 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800800 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 if (portalToDisplayId != ADISPLAY_ID_NONE &&
802 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800803 if (addPortalWindows) {
804 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700805 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800806 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700807 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 // Found window.
811 return windowHandle;
812 }
813 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800814
Michael Wright44753b12020-07-08 13:48:11 +0100815 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700816 touchState->addOrUpdateWindow(windowHandle,
817 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
818 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
822 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700823 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824}
825
Garfield Tane84e6f92019-08-29 17:28:41 -0700826std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700827 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000828 std::vector<TouchedMonitor> touchedMonitors;
829
830 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
831 addGestureMonitors(monitors, touchedMonitors);
832 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
833 const InputWindowInfo* windowInfo = portalWindow->getInfo();
834 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
836 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000837 }
838 return touchedMonitors;
839}
840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700841void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 const char* reason;
843 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700848 reason = "inbound event was dropped because the policy consumed it";
849 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700850 case DropReason::DISABLED:
851 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 ALOGI("Dropped event because input dispatch is disabled.");
853 }
854 reason = "inbound event was dropped because input dispatch is disabled";
855 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700856 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 ALOGI("Dropped event because of pending overdue app switch.");
858 reason = "inbound event was dropped because of pending overdue app switch";
859 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 ALOGI("Dropped event because the current application is not responding and the user "
862 "has started interacting with a different application.");
863 reason = "inbound event was dropped because the current application is not responding "
864 "and the user has started interacting with a different application";
865 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 ALOGI("Dropped event because it is stale.");
868 reason = "inbound event was dropped because it is stale";
869 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 case DropReason::NOT_DROPPED: {
871 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700876 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700877 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
879 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700882 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700883 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
884 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
886 synthesizeCancelationEventsForAllConnectionsLocked(options);
887 } else {
888 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
889 synthesizeCancelationEventsForAllConnectionsLocked(options);
890 }
891 break;
892 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100893 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700894 case EventEntry::Type::CONFIGURATION_CHANGED:
895 case EventEntry::Type::DEVICE_RESET: {
896 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
897 break;
898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900}
901
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800902static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
904 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905}
906
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700907bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
908 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
909 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
910 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911}
912
913bool InputDispatcher::isAppSwitchPendingLocked() {
914 return mAppSwitchDueTime != LONG_LONG_MAX;
915}
916
917void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
918 mAppSwitchDueTime = LONG_LONG_MAX;
919
920#if DEBUG_APP_SWITCH
921 if (handled) {
922 ALOGD("App switch has arrived.");
923 } else {
924 ALOGD("App switch was abandoned.");
925 }
926#endif
927}
928
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700930 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931}
932
933bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700934 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 return false;
936 }
937
938 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700939 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700940 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700942 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943
944 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700945 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 return true;
947}
948
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700949void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
950 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951}
952
953void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700954 while (!mInboundQueue.empty()) {
955 EventEntry* entry = mInboundQueue.front();
956 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 releaseInboundEventLocked(entry);
958 }
959 traceInboundQueueLengthLocked();
960}
961
962void InputDispatcher::releasePendingEventLocked() {
963 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700965 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967}
968
969void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
970 InjectionState* injectionState = entry->injectionState;
971 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
972#if DEBUG_DISPATCH_CYCLE
973 ALOGD("Injected inbound event was dropped.");
974#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800975 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
977 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700978 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980 addRecentEventLocked(entry);
981 entry->release();
982}
983
984void InputDispatcher::resetKeyRepeatLocked() {
985 if (mKeyRepeatState.lastKeyEntry) {
986 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700987 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 }
989}
990
Garfield Tane84e6f92019-08-29 17:28:41 -0700991KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
993
994 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700995 uint32_t policyFlags = entry->policyFlags &
996 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 if (entry->refCount == 1) {
998 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800999 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 entry->eventTime = currentTime;
1001 entry->policyFlags = policyFlags;
1002 entry->repeatCount += 1;
1003 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001005 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001006 entry->displayId, policyFlags, entry->action, entry->flags,
1007 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010 mKeyRepeatState.lastKeyEntry = newEntry;
1011 entry->release();
1012
1013 entry = newEntry;
1014 }
1015 entry->syntheticRepeat = true;
1016
1017 // Increment reference count since we keep a reference to the event in
1018 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1019 entry->refCount += 1;
1020
1021 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1022 return entry;
1023}
1024
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1026 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001028 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029#endif
1030
1031 // Reset key repeating in case a keyboard device was added or removed or something.
1032 resetKeyRepeatLocked();
1033
1034 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001035 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1036 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001038 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 return true;
1040}
1041
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001044 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046#endif
1047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 options.deviceId = entry->deviceId;
1050 synthesizeCancelationEventsForAllConnectionsLocked(options);
1051 return true;
1052}
1053
Vishnu Nairad321cd2020-08-20 16:40:21 -07001054void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001055 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001056 if (mPendingEvent != nullptr) {
1057 // Move the pending event to the front of the queue. This will give the chance
1058 // for the pending event to get dispatched to the newly focused window
1059 mInboundQueue.push_front(mPendingEvent);
1060 mPendingEvent = nullptr;
1061 }
1062
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001063 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001064 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001065
1066 // This event should go to the front of the queue, but behind all other focus events
1067 // Find the last focus event, and insert right after it
1068 std::deque<EventEntry*>::reverse_iterator it =
1069 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1070 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1071
1072 // Maintain the order of focus events. Insert the entry after all other focus events.
1073 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001074}
1075
1076void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001077 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001078 if (channel == nullptr) {
1079 return; // Window has gone away
1080 }
1081 InputTarget target;
1082 target.inputChannel = channel;
1083 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1084 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001085 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1086 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001087 std::string reason = std::string("reason=").append(entry->reason);
1088 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 dispatchEventLocked(currentTime, entry, {target});
1090}
1091
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 if (!entry->dispatchInProgress) {
1096 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1097 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1098 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1099 if (mKeyRepeatState.lastKeyEntry &&
1100 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 // We have seen two identical key downs in a row which indicates that the device
1102 // driver is automatically generating key repeats itself. We take note of the
1103 // repeat here, but we disable our own next key repeat timer since it is clear that
1104 // we will not need to synthesize key repeats ourselves.
1105 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1106 resetKeyRepeatLocked();
1107 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1108 } else {
1109 // Not a repeat. Save key down state in case we do see a repeat later.
1110 resetKeyRepeatLocked();
1111 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1112 }
1113 mKeyRepeatState.lastKeyEntry = entry;
1114 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 resetKeyRepeatLocked();
1117 }
1118
1119 if (entry->repeatCount == 1) {
1120 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1121 } else {
1122 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1123 }
1124
1125 entry->dispatchInProgress = true;
1126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129
1130 // Handle case where the policy asked us to try again later last time.
1131 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1132 if (currentTime < entry->interceptKeyWakeupTime) {
1133 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1134 *nextWakeupTime = entry->interceptKeyWakeupTime;
1135 }
1136 return false; // wait until next wakeup
1137 }
1138 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1139 entry->interceptKeyWakeupTime = 0;
1140 }
1141
1142 // Give the policy a chance to intercept the key.
1143 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1144 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001145 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001146 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001147 sp<IBinder> focusedWindowToken =
1148 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1149 if (focusedWindowToken != nullptr) {
1150 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001153 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 entry->refCount += 1;
1155 return false; // wait for the command to run
1156 } else {
1157 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1158 }
1159 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001160 if (*dropReason == DropReason::NOT_DROPPED) {
1161 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163 }
1164
1165 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001168 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001170 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 return true;
1172 }
1173
1174 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001175 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001177 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1179 return false;
1180 }
1181
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001182 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1184 return true;
1185 }
1186
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001187 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189
1190 // Dispatch the key.
1191 dispatchEventLocked(currentTime, entry, inputTargets);
1192 return true;
1193}
1194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001195void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001197 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1199 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1201 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1202 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203#endif
1204}
1205
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1207 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001208 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 entry->dispatchInProgress = true;
1212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
1215
1216 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001217 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001219 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001220 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 return true;
1222 }
1223
1224 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1225
1226 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001227 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228
1229 bool conflictingPointerActions = false;
1230 int32_t injectionResult;
1231 if (isPointerEvent) {
1232 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001234 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 } else {
1237 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1242 return false;
1243 }
1244
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001245 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001246 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1247 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1248 return true;
1249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001251 CancelationOptions::Mode mode(isPointerEvent
1252 ? CancelationOptions::CANCEL_POINTER_EVENTS
1253 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1254 CancelationOptions options(mode, "input event injection failed");
1255 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 return true;
1257 }
1258
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001259 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001262 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001263 std::unordered_map<int32_t, TouchState>::iterator it =
1264 mTouchStatesByDisplay.find(entry->displayId);
1265 if (it != mTouchStatesByDisplay.end()) {
1266 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001267 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001268 // The event has gone through these portal windows, so we add monitoring targets of
1269 // the corresponding displays as well.
1270 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001271 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001272 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001273 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001274 }
1275 }
1276 }
1277 }
1278
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 // Dispatch the motion.
1280 if (conflictingPointerActions) {
1281 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 synthesizeCancelationEventsForAllConnectionsLocked(options);
1284 }
1285 dispatchEventLocked(currentTime, entry, inputTargets);
1286 return true;
1287}
1288
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001289void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001291 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 ", policyFlags=0x%x, "
1293 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1294 "metaState=0x%x, buttonState=0x%x,"
1295 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001296 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1297 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1298 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001302 "x=%f, y=%f, pressure=%f, size=%f, "
1303 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1304 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001305 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1306 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1307 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1308 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1309 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1310 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1311 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1312 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1313 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1314 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
1316#endif
1317}
1318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1320 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001321 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322#if DEBUG_DISPATCH_CYCLE
1323 ALOGD("dispatchEventToCurrentInputTargets");
1324#endif
1325
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001326 updateInteractionTokensLocked(*eventEntry, inputTargets);
1327
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1329
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001332 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001333 sp<Connection> connection =
1334 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001335 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001336 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001338 if (DEBUG_FOCUS) {
1339 ALOGD("Dropping event delivery to target with channel '%s' because it "
1340 "is no longer registered with the input dispatcher.",
1341 inputTarget.inputChannel->getName().c_str());
1342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344 }
1345}
1346
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001347void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1348 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1349 // If the policy decides to close the app, we will get a channel removal event via
1350 // unregisterInputChannel, and will clean up the connection that way. We are already not
1351 // sending new pointers to the connection when it blocked, but focused events will continue to
1352 // pile up.
1353 ALOGW("Canceling events for %s because it is unresponsive",
1354 connection->inputChannel->getName().c_str());
1355 if (connection->status == Connection::STATUS_NORMAL) {
1356 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1357 "application not responding");
1358 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360}
1361
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001362void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001363 if (DEBUG_FOCUS) {
1364 ALOGD("Resetting ANR timeouts.");
1365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
1367 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001368 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001369 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
Tiger Huang721e26f2018-07-24 22:26:19 +08001372/**
1373 * Get the display id that the given event should go to. If this event specifies a valid display id,
1374 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1375 * Focused display is the display that the user most recently interacted with.
1376 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001377int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001378 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001380 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1382 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 break;
1384 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001385 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1387 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 break;
1389 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001390 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001391 case EventEntry::Type::CONFIGURATION_CHANGED:
1392 case EventEntry::Type::DEVICE_RESET: {
1393 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 return ADISPLAY_ID_NONE;
1395 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001396 }
1397 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1398}
1399
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001400bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1401 const char* focusedWindowName) {
1402 if (mAnrTracker.empty()) {
1403 // already processed all events that we waited for
1404 mKeyIsWaitingForEventsTimeout = std::nullopt;
1405 return false;
1406 }
1407
1408 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1409 // Start the timer
1410 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1411 "focus to change",
1412 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001413 mKeyIsWaitingForEventsTimeout = currentTime +
1414 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1415 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001416 return true;
1417 }
1418
1419 // We still have pending events, and already started the timer
1420 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1421 return true; // Still waiting
1422 }
1423
1424 // Waited too long, and some connection still hasn't processed all motions
1425 // Just send the key to the focused window
1426 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1427 focusedWindowName);
1428 mKeyIsWaitingForEventsTimeout = std::nullopt;
1429 return false;
1430}
1431
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 std::vector<InputTarget>& inputTargets,
1435 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001436 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437
Tiger Huang721e26f2018-07-24 22:26:19 +08001438 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001439 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001440 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001441 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1442
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 // If there is no currently focused window and no focused application
1444 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001445 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1446 ALOGI("Dropping %s event because there is no focused window or focused application in "
1447 "display %" PRId32 ".",
1448 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001449 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
1451
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001452 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1453 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1454 // start interacting with another application via touch (app switch). This code can be removed
1455 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1456 // an app is expected to have a focused window.
1457 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1458 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1459 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001460 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1461 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1462 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463 mAwaitedFocusedApplication = focusedApplicationHandle;
1464 ALOGW("Waiting because no window has focus but %s may eventually add a "
1465 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001466 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001467 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1468 return INPUT_EVENT_INJECTION_PENDING;
1469 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1470 // Already raised ANR. Drop the event
1471 ALOGE("Dropping %s event because there is no focused window",
1472 EventEntry::typeToString(entry.type));
1473 return INPUT_EVENT_INJECTION_FAILED;
1474 } else {
1475 // Still waiting for the focused window
1476 return INPUT_EVENT_INJECTION_PENDING;
1477 }
1478 }
1479
1480 // we have a valid, non-null focused window
1481 resetNoFocusedWindowTimeoutLocked();
1482
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001484 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001485 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001488 if (focusedWindowHandle->getInfo()->paused) {
1489 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1490 return INPUT_EVENT_INJECTION_PENDING;
1491 }
1492
1493 // If the event is a key event, then we must wait for all previous events to
1494 // complete before delivering it because previous events may have the
1495 // side-effect of transferring focus to a different window and we want to
1496 // ensure that the following keys are sent to the new window.
1497 //
1498 // Suppose the user touches a button in a window then immediately presses "A".
1499 // If the button causes a pop-up window to appear then we want to ensure that
1500 // the "A" key is delivered to the new pop-up window. This is because users
1501 // often anticipate pending UI changes when typing on a keyboard.
1502 // To obtain this behavior, we must serialize key events with respect to all
1503 // prior input events.
1504 if (entry.type == EventEntry::Type::KEY) {
1505 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1506 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1507 return INPUT_EVENT_INJECTION_PENDING;
1508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510
1511 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001512 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001513 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1514 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515
1516 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001517 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518}
1519
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001520/**
1521 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1522 * that are currently unresponsive.
1523 */
1524std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1525 const std::vector<TouchedMonitor>& monitors) const {
1526 std::vector<TouchedMonitor> responsiveMonitors;
1527 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1528 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1529 sp<Connection> connection = getConnectionLocked(
1530 monitor.monitor.inputChannel->getConnectionToken());
1531 if (connection == nullptr) {
1532 ALOGE("Could not find connection for monitor %s",
1533 monitor.monitor.inputChannel->getName().c_str());
1534 return false;
1535 }
1536 if (!connection->responsive) {
1537 ALOGW("Unresponsive monitor %s will not get the new gesture",
1538 connection->inputChannel->getName().c_str());
1539 return false;
1540 }
1541 return true;
1542 });
1543 return responsiveMonitors;
1544}
1545
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 std::vector<InputTarget>& inputTargets,
1549 nsecs_t* nextWakeupTime,
1550 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001551 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 enum InjectionPermission {
1553 INJECTION_PERMISSION_UNKNOWN,
1554 INJECTION_PERMISSION_GRANTED,
1555 INJECTION_PERMISSION_DENIED
1556 };
1557
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 // For security reasons, we defer updating the touch state until we are sure that
1559 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001560 int32_t displayId = entry.displayId;
1561 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1563
1564 // Update the touch state as needed based on the properties of the touch event.
1565 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1566 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001567 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1568 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001570 // Copy current touch state into tempTouchState.
1571 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1572 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001573 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001574 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001575 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1576 mTouchStatesByDisplay.find(displayId);
1577 if (oldStateIt != mTouchStatesByDisplay.end()) {
1578 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001579 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001580 }
1581
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001582 bool isSplit = tempTouchState.split;
1583 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1584 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1585 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001586 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1587 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1588 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1589 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1590 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001591 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 bool wrongDevice = false;
1593 if (newGesture) {
1594 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001595 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001596 ALOGI("Dropping event because a pointer for a different device is already down "
1597 "in display %" PRId32,
1598 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001599 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1601 switchedDevice = false;
1602 wrongDevice = true;
1603 goto Failed;
1604 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001605 tempTouchState.reset();
1606 tempTouchState.down = down;
1607 tempTouchState.deviceId = entry.deviceId;
1608 tempTouchState.source = entry.source;
1609 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001611 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001612 ALOGI("Dropping move event because a pointer for a different device is already active "
1613 "in display %" PRId32,
1614 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001615 // TODO: test multiple simultaneous input streams.
1616 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1617 switchedDevice = false;
1618 wrongDevice = true;
1619 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 }
1621
1622 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1623 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1624
Garfield Tan00f511d2019-06-12 16:55:40 -07001625 int32_t x;
1626 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001628 // Always dispatch mouse events to cursor position.
1629 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001630 x = int32_t(entry.xCursorPosition);
1631 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001632 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1634 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001635 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001636 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001637 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001638 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1639 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001640
1641 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001642 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001643 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 if (newTouchedWindowHandle != nullptr &&
1647 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001648 // New window supports splitting, but we should never split mouse events.
1649 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 } else if (isSplit) {
1651 // New window does not support splitting but we have already split events.
1652 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001653 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 }
1655
1656 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001657 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001659 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001660 }
1661
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001662 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1663 ALOGI("Not sending touch event to %s because it is paused",
1664 newTouchedWindowHandle->getName().c_str());
1665 newTouchedWindowHandle = nullptr;
1666 }
1667
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001668 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001669 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001670 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1671 if (!isResponsive) {
1672 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001673 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1674 newTouchedWindowHandle = nullptr;
1675 }
1676 }
1677
1678 // Also don't send the new touch event to unresponsive gesture monitors
1679 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1680
Michael Wright3dd60e22019-03-27 22:06:44 +00001681 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1682 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001683 "(%d, %d) in display %" PRId32 ".",
1684 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001685 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1686 goto Failed;
1687 }
1688
1689 if (newTouchedWindowHandle != nullptr) {
1690 // Set target flags.
1691 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1692 if (isSplit) {
1693 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001695 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1696 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1697 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1698 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1699 }
1700
1701 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001702 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1703 newHoverWindowHandle = nullptr;
1704 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 }
1707
1708 // Update the temporary touch state.
1709 BitSet32 pointerIds;
1710 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001712 pointerIds.markBit(pointerId);
1713 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001714 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
1716
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001717 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 } else {
1719 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1720
1721 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001722 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001723 if (DEBUG_FOCUS) {
1724 ALOGD("Dropping event because the pointer is not down or we previously "
1725 "dropped the pointer down event in display %" PRId32,
1726 displayId);
1727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1729 goto Failed;
1730 }
1731
1732 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001734 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1736 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
1738 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001739 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001740 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1742 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001743 if (DEBUG_FOCUS) {
1744 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1745 oldTouchedWindowHandle->getName().c_str(),
1746 newTouchedWindowHandle->getName().c_str(), displayId);
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001749 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1750 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1751 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752
1753 // Make a slippery entrance into the new window.
1754 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1755 isSplit = true;
1756 }
1757
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001758 int32_t targetFlags =
1759 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 if (isSplit) {
1761 targetFlags |= InputTarget::FLAG_SPLIT;
1762 }
1763 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1764 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1765 }
1766
1767 BitSet32 pointerIds;
1768 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001771 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 }
1773 }
1774 }
1775
1776 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001777 // Let the previous window know that the hover sequence is over, unless we already did it
1778 // when dispatching it as is to newTouchedWindowHandle.
1779 if (mLastHoverWindowHandle != nullptr &&
1780 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1781 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782#if DEBUG_HOVER
1783 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001786 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1787 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
1789
Garfield Tandf26e862020-07-01 20:18:19 -07001790 // Let the new window know that the hover sequence is starting, unless we already did it
1791 // when dispatching it as is to newTouchedWindowHandle.
1792 if (newHoverWindowHandle != nullptr &&
1793 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1794 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795#if DEBUG_HOVER
1796 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001799 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1800 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1801 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 }
1803 }
1804
1805 // Check permission to inject into all touched foreground windows and ensure there
1806 // is at least one touched foreground window.
1807 {
1808 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001809 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1811 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1814 injectionPermission = INJECTION_PERMISSION_DENIED;
1815 goto Failed;
1816 }
1817 }
1818 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001819 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001820 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001821 ALOGI("Dropping event because there is no touched foreground window in display "
1822 "%" PRId32 " or gesture monitor to receive it.",
1823 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1825 goto Failed;
1826 }
1827
1828 // Permission granted to injection into all touched foreground windows.
1829 injectionPermission = INJECTION_PERMISSION_GRANTED;
1830 }
1831
1832 // Check whether windows listening for outside touches are owned by the same UID. If it is
1833 // set the policy flag that we will not reveal coordinate information to this window.
1834 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1835 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001837 if (foregroundWindowHandle) {
1838 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001839 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001840 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1841 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1842 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1844 InputTarget::FLAG_ZERO_COORDS,
1845 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
1848 }
1849 }
1850 }
1851
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 // If this is the first pointer going down and the touched window has a wallpaper
1853 // then also add the touched wallpaper windows so they are locked in for the duration
1854 // of the touch gesture.
1855 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1856 // engine only supports touch events. We would need to add a mechanism similar
1857 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1858 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1859 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001862 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001863 getWindowHandlesLocked(displayId);
1864 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001866 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001867 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001868 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 .addOrUpdateWindow(windowHandle,
1870 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1871 InputTarget::
1872 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1873 InputTarget::FLAG_DISPATCH_AS_IS,
1874 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876 }
1877 }
1878 }
1879
1880 // Success! Output targets.
1881 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1882
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001883 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
1887
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001889 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001891 }
1892
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 // Drop the outside or hover touch windows since we will not care about them
1894 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001895 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896
1897Failed:
1898 // Check injection permission once and for all.
1899 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001900 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 injectionPermission = INJECTION_PERMISSION_GRANTED;
1902 } else {
1903 injectionPermission = INJECTION_PERMISSION_DENIED;
1904 }
1905 }
1906
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001907 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1908 return injectionResult;
1909 }
1910
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001912 if (!wrongDevice) {
1913 if (switchedDevice) {
1914 if (DEBUG_FOCUS) {
1915 ALOGD("Conflicting pointer actions: Switched to a different device.");
1916 }
1917 *outConflictingPointerActions = true;
1918 }
1919
1920 if (isHoverAction) {
1921 // Started hovering, therefore no longer down.
1922 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001923 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001924 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1925 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 *outConflictingPointerActions = true;
1928 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001929 tempTouchState.reset();
1930 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1931 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1932 tempTouchState.deviceId = entry.deviceId;
1933 tempTouchState.source = entry.source;
1934 tempTouchState.displayId = displayId;
1935 }
1936 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1937 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1938 // All pointers up or canceled.
1939 tempTouchState.reset();
1940 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1941 // First pointer went down.
1942 if (oldState && oldState->down) {
1943 if (DEBUG_FOCUS) {
1944 ALOGD("Conflicting pointer actions: Down received while already down.");
1945 }
1946 *outConflictingPointerActions = true;
1947 }
1948 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1949 // One pointer went up.
1950 if (isSplit) {
1951 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1952 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001954 for (size_t i = 0; i < tempTouchState.windows.size();) {
1955 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1956 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1957 touchedWindow.pointerIds.clearBit(pointerId);
1958 if (touchedWindow.pointerIds.isEmpty()) {
1959 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1960 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001963 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001965 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001966 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001967
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001968 // Save changes unless the action was scroll in which case the temporary touch
1969 // state was only valid for this one action.
1970 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1971 if (tempTouchState.displayId >= 0) {
1972 mTouchStatesByDisplay[displayId] = tempTouchState;
1973 } else {
1974 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 // Update hover state.
1979 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 return injectionResult;
1983}
1984
1985void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001986 int32_t targetFlags, BitSet32 pointerIds,
1987 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001988 std::vector<InputTarget>::iterator it =
1989 std::find_if(inputTargets.begin(), inputTargets.end(),
1990 [&windowHandle](const InputTarget& inputTarget) {
1991 return inputTarget.inputChannel->getConnectionToken() ==
1992 windowHandle->getToken();
1993 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001994
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001995 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001996
1997 if (it == inputTargets.end()) {
1998 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001999 std::shared_ptr<InputChannel> inputChannel =
2000 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002001 if (inputChannel == nullptr) {
2002 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2003 return;
2004 }
2005 inputTarget.inputChannel = inputChannel;
2006 inputTarget.flags = targetFlags;
2007 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2008 inputTargets.push_back(inputTarget);
2009 it = inputTargets.end() - 1;
2010 }
2011
2012 ALOG_ASSERT(it->flags == targetFlags);
2013 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2014
chaviw1ff3d1e2020-07-01 15:53:47 -07002015 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016}
2017
Michael Wright3dd60e22019-03-27 22:06:44 +00002018void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002019 int32_t displayId, float xOffset,
2020 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002021 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2022 mGlobalMonitorsByDisplay.find(displayId);
2023
2024 if (it != mGlobalMonitorsByDisplay.end()) {
2025 const std::vector<Monitor>& monitors = it->second;
2026 for (const Monitor& monitor : monitors) {
2027 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 }
2030}
2031
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002032void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2033 float yOffset,
2034 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 InputTarget target;
2036 target.inputChannel = monitor.inputChannel;
2037 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002038 ui::Transform t;
2039 t.set(xOffset, yOffset);
2040 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 inputTargets.push_back(target);
2042}
2043
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 const InjectionState* injectionState) {
2046 if (injectionState &&
2047 (windowHandle == nullptr ||
2048 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2049 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002050 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 "owned by uid %d",
2053 injectionState->injectorPid, injectionState->injectorUid,
2054 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 } else {
2056 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
2059 return false;
2060 }
2061 return true;
2062}
2063
Robert Carrc9bf1d32020-04-13 17:21:08 -07002064/**
2065 * Indicate whether one window handle should be considered as obscuring
2066 * another window handle. We only check a few preconditions. Actually
2067 * checking the bounds is left to the caller.
2068 */
2069static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2070 const sp<InputWindowHandle>& otherHandle) {
2071 // Compare by token so cloned layers aren't counted
2072 if (haveSameToken(windowHandle, otherHandle)) {
2073 return false;
2074 }
2075 auto info = windowHandle->getInfo();
2076 auto otherInfo = otherHandle->getInfo();
2077 if (!otherInfo->visible) {
2078 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002079 } else if (info->ownerPid == otherInfo->ownerPid) {
2080 // If ownerPid is the same we don't generate occlusion events as there
2081 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002082 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002083 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002084 return false;
2085 } else if (otherInfo->displayId != info->displayId) {
2086 return false;
2087 }
2088 return true;
2089}
2090
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002091bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2092 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002094 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002095 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002096 if (windowHandle == otherHandle) {
2097 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002100 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002101 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 return true;
2103 }
2104 }
2105 return false;
2106}
2107
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002108bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2109 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002110 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002111 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002112 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002113 if (windowHandle == otherHandle) {
2114 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002115 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002116 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002117 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002118 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002119 return true;
2120 }
2121 }
2122 return false;
2123}
2124
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002125std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002126 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002128 if (applicationHandle != nullptr) {
2129 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002130 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 } else {
2132 return applicationHandle->getName();
2133 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002134 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002135 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002137 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139}
2140
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002141void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002142 if (eventEntry.type == EventEntry::Type::FOCUS) {
2143 // Focus events are passed to apps, but do not represent user activity.
2144 return;
2145 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002146 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002147 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002148 if (focusedWindowHandle != nullptr) {
2149 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002150 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002152 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153#endif
2154 return;
2155 }
2156 }
2157
2158 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002160 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002161 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2162 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 return;
2164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002166 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 eventType = USER_ACTIVITY_EVENT_TOUCH;
2168 }
2169 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002171 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2173 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 return;
2175 }
2176 eventType = USER_ACTIVITY_EVENT_BUTTON;
2177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002179 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002180 case EventEntry::Type::CONFIGURATION_CHANGED:
2181 case EventEntry::Type::DEVICE_RESET: {
2182 LOG_ALWAYS_FATAL("%s events are not user activity",
2183 EventEntry::typeToString(eventEntry.type));
2184 break;
2185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002188 std::unique_ptr<CommandEntry> commandEntry =
2189 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002192 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193}
2194
2195void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002196 const sp<Connection>& connection,
2197 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002198 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002199 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002200 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002201 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002202 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002203 ATRACE_NAME(message.c_str());
2204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205#if DEBUG_DISPATCH_CYCLE
2206 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002207 "globalScaleFactor=%f, pointerIds=0x%x %s",
2208 connection->getInputChannelName().c_str(), inputTarget.flags,
2209 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2210 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211#endif
2212
2213 // Skip this event if the connection status is not normal.
2214 // We don't want to enqueue additional outbound events if the connection is broken.
2215 if (connection->status != Connection::STATUS_NORMAL) {
2216#if DEBUG_DISPATCH_CYCLE
2217 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002218 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219#endif
2220 return;
2221 }
2222
2223 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002224 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2225 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2226 "Entry type %s should not have FLAG_SPLIT",
2227 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002229 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002230 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002232 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 if (!splitMotionEntry) {
2234 return; // split event was dropped
2235 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002236 if (DEBUG_FOCUS) {
2237 ALOGD("channel '%s' ~ Split motion event.",
2238 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002239 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002240 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 splitMotionEntry->release();
2243 return;
2244 }
2245 }
2246
2247 // Not splitting. Enqueue dispatch entries for the event as is.
2248 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2249}
2250
2251void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 const sp<Connection>& connection,
2253 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002254 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002255 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002257 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002258 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002259 ATRACE_NAME(message.c_str());
2260 }
2261
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002262 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263
2264 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002265 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002266 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002267 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002269 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
2278 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002279 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 startDispatchCycleLocked(currentTime, connection);
2281 }
2282}
2283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2285 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002286 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002288 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2290 connection->getInputChannelName().c_str(),
2291 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002292 ATRACE_NAME(message.c_str());
2293 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002294 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 if (!(inputTargetFlags & dispatchMode)) {
2296 return;
2297 }
2298 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2299
2300 // This is a new event.
2301 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002302 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002303 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002305 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2306 // different EventEntry than what was passed in.
2307 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002309 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002310 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002311 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002312 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002313 dispatchEntry->resolvedAction = keyEntry.action;
2314 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002316 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2317 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2320 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002322 return; // skip the inconsistent event
2323 }
2324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002327 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002329 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2330 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2331 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2332 static_cast<int32_t>(IdGenerator::Source::OTHER);
2333 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2336 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2338 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2340 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2342 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2344 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002345 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002346 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 }
2348 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002349 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2350 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2353 "event",
2354 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2361 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2362 }
2363 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2364 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2368 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2371 "event",
2372 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 return; // skip the inconsistent event
2375 }
2376
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002377 dispatchEntry->resolvedEventId =
2378 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2379 ? mIdGenerator.nextId()
2380 : motionEntry.id;
2381 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2382 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2383 ") to MotionEvent(id=0x%" PRIx32 ").",
2384 motionEntry.id, dispatchEntry->resolvedEventId);
2385 ATRACE_NAME(message.c_str());
2386 }
2387
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002388 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002389 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390
2391 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002393 case EventEntry::Type::FOCUS: {
2394 break;
2395 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002396 case EventEntry::Type::CONFIGURATION_CHANGED:
2397 case EventEntry::Type::DEVICE_RESET: {
2398 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002399 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002400 break;
2401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
2403
2404 // Remember that we are waiting for this dispatch to complete.
2405 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002406 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
2408
2409 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002410 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002411 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002412}
2413
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002414/**
2415 * This function is purely for debugging. It helps us understand where the user interaction
2416 * was taking place. For example, if user is touching launcher, we will see a log that user
2417 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2418 * We will see both launcher and wallpaper in that list.
2419 * Once the interaction with a particular set of connections starts, no new logs will be printed
2420 * until the set of interacted connections changes.
2421 *
2422 * The following items are skipped, to reduce the logspam:
2423 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2424 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2425 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2426 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2427 * Both of those ACTION_UP events would not be logged
2428 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2429 * will not be logged. This is omitted to reduce the amount of data printed.
2430 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2431 * gesture monitor is the only connection receiving the remainder of the gesture.
2432 */
2433void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2434 const std::vector<InputTarget>& targets) {
2435 // Skip ACTION_UP events, and all events other than keys and motions
2436 if (entry.type == EventEntry::Type::KEY) {
2437 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2438 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2439 return;
2440 }
2441 } else if (entry.type == EventEntry::Type::MOTION) {
2442 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2443 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2444 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2445 return;
2446 }
2447 } else {
2448 return; // Not a key or a motion
2449 }
2450
2451 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2452 std::vector<sp<Connection>> newConnections;
2453 for (const InputTarget& target : targets) {
2454 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2455 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2456 continue; // Skip windows that receive ACTION_OUTSIDE
2457 }
2458
2459 sp<IBinder> token = target.inputChannel->getConnectionToken();
2460 sp<Connection> connection = getConnectionLocked(token);
2461 if (connection == nullptr || connection->monitor) {
2462 continue; // We only need to keep track of the non-monitor connections.
2463 }
2464 newConnectionTokens.insert(std::move(token));
2465 newConnections.emplace_back(connection);
2466 }
2467 if (newConnectionTokens == mInteractionConnectionTokens) {
2468 return; // no change
2469 }
2470 mInteractionConnectionTokens = newConnectionTokens;
2471
2472 std::string windowList;
2473 for (const sp<Connection>& connection : newConnections) {
2474 windowList += connection->getWindowName() + ", ";
2475 }
2476 std::string message = "Interaction with windows: " + windowList;
2477 if (windowList.empty()) {
2478 message += "<none>";
2479 }
2480 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2481}
2482
chaviwfd6d3512019-03-25 13:23:49 -07002483void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002484 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002485 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002486 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2487 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002488 return;
2489 }
2490
Vishnu Nairad321cd2020-08-20 16:40:21 -07002491 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2492 if (focusedToken == token) {
2493 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002494 return;
2495 }
2496
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002497 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2498 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002499 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002500 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501}
2502
2503void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002505 if (ATRACE_ENABLED()) {
2506 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002508 ATRACE_NAME(message.c_str());
2509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512#endif
2513
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002514 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2515 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002517 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002518 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002519 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520
2521 // Publish the event.
2522 status_t status;
2523 EventEntry* eventEntry = dispatchEntry->eventEntry;
2524 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002525 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002526 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2527 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002530 status =
2531 connection->inputPublisher
2532 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2533 keyEntry->deviceId, keyEntry->source,
2534 keyEntry->displayId, std::move(hmac),
2535 dispatchEntry->resolvedAction,
2536 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2537 keyEntry->scanCode, keyEntry->metaState,
2538 keyEntry->repeatCount, keyEntry->downTime,
2539 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002543 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 PointerCoords scaledCoords[MAX_POINTERS];
2547 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2548
chaviw82357092020-01-28 13:13:06 -08002549 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002550 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2551 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2552 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002553 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2555 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002556 // Don't apply window scale here since we don't want scale to affect raw
2557 // coordinates. The scale will be sent back to the client and applied
2558 // later when requesting relative coordinates.
2559 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2560 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 }
2562 usingCoords = scaledCoords;
2563 }
2564 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002565 // We don't want the dispatch target to know.
2566 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2567 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2568 scaledCoords[i].clear();
2569 }
2570 usingCoords = scaledCoords;
2571 }
2572 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002573
2574 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575
2576 // Publish the motion event.
2577 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002578 .publishMotionEvent(dispatchEntry->seq,
2579 dispatchEntry->resolvedEventId,
2580 motionEntry->deviceId, motionEntry->source,
2581 motionEntry->displayId, std::move(hmac),
2582 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 motionEntry->actionButton,
2584 dispatchEntry->resolvedFlags,
2585 motionEntry->edgeFlags, motionEntry->metaState,
2586 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002587 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002588 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002589 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002590 motionEntry->yPrecision,
2591 motionEntry->xCursorPosition,
2592 motionEntry->yCursorPosition,
2593 motionEntry->downTime, motionEntry->eventTime,
2594 motionEntry->pointerCount,
2595 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002596 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002597 break;
2598 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002599 case EventEntry::Type::FOCUS: {
2600 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2601 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002602 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002603 focusEntry->hasFocus,
2604 mInTouchMode);
2605 break;
2606 }
2607
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002608 case EventEntry::Type::CONFIGURATION_CHANGED:
2609 case EventEntry::Type::DEVICE_RESET: {
2610 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2611 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615
2616 // Check the result.
2617 if (status) {
2618 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002619 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 "This is unexpected because the wait queue is empty, so the pipe "
2622 "should be empty and we shouldn't have any problems writing an "
2623 "event to it, status=%d",
2624 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2626 } else {
2627 // Pipe is full and we are waiting for the app to finish process some events
2628 // before sending more events to it.
2629#if DEBUG_DISPATCH_CYCLE
2630 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 "waiting for the application to catch up",
2632 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 }
2635 } else {
2636 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002637 "status=%d",
2638 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2640 }
2641 return;
2642 }
2643
2644 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002645 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2646 connection->outboundQueue.end(),
2647 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002648 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002649 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002650 if (connection->responsive) {
2651 mAnrTracker.insert(dispatchEntry->timeoutTime,
2652 connection->inputChannel->getConnectionToken());
2653 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002654 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
2656}
2657
chaviw09c8d2d2020-08-24 15:48:26 -07002658std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2659 size_t size;
2660 switch (event.type) {
2661 case VerifiedInputEvent::Type::KEY: {
2662 size = sizeof(VerifiedKeyEvent);
2663 break;
2664 }
2665 case VerifiedInputEvent::Type::MOTION: {
2666 size = sizeof(VerifiedMotionEvent);
2667 break;
2668 }
2669 }
2670 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2671 return mHmacKeyManager.sign(start, size);
2672}
2673
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002674const std::array<uint8_t, 32> InputDispatcher::getSignature(
2675 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2676 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2677 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2678 // Only sign events up and down events as the purely move events
2679 // are tied to their up/down counterparts so signing would be redundant.
2680 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2681 verifiedEvent.actionMasked = actionMasked;
2682 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002683 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002684 }
2685 return INVALID_HMAC;
2686}
2687
2688const std::array<uint8_t, 32> InputDispatcher::getSignature(
2689 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2690 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2691 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2692 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002693 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002694}
2695
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 const sp<Connection>& connection, uint32_t seq,
2698 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699#if DEBUG_DISPATCH_CYCLE
2700 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702#endif
2703
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 if (connection->status == Connection::STATUS_BROKEN ||
2705 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 return;
2707 }
2708
2709 // Notify other system components and prepare to start the next dispatch cycle.
2710 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2711}
2712
2713void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 const sp<Connection>& connection,
2715 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#if DEBUG_DISPATCH_CYCLE
2717 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#endif
2720
2721 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002722 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002723 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002724 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002725 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
2727 // The connection appears to be unrecoverably broken.
2728 // Ignore already broken or zombie connections.
2729 if (connection->status == Connection::STATUS_NORMAL) {
2730 connection->status = Connection::STATUS_BROKEN;
2731
2732 if (notify) {
2733 // Notify other system components.
2734 onDispatchCycleBrokenLocked(currentTime, connection);
2735 }
2736 }
2737}
2738
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002739void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2740 while (!queue.empty()) {
2741 DispatchEntry* dispatchEntry = queue.front();
2742 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002743 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745}
2746
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002747void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002749 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 }
2751 delete dispatchEntry;
2752}
2753
2754int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2755 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2756
2757 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002758 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002760 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 "fd=%d, events=0x%x",
2763 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764 return 0; // remove the callback
2765 }
2766
2767 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002768 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2770 if (!(events & ALOOPER_EVENT_INPUT)) {
2771 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772 "events=0x%x",
2773 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 return 1;
2775 }
2776
2777 nsecs_t currentTime = now();
2778 bool gotOne = false;
2779 status_t status;
2780 for (;;) {
2781 uint32_t seq;
2782 bool handled;
2783 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2784 if (status) {
2785 break;
2786 }
2787 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2788 gotOne = true;
2789 }
2790 if (gotOne) {
2791 d->runCommandsLockedInterruptible();
2792 if (status == WOULD_BLOCK) {
2793 return 1;
2794 }
2795 }
2796
2797 notify = status != DEAD_OBJECT || !connection->monitor;
2798 if (notify) {
2799 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 }
2802 } else {
2803 // Monitor channels are never explicitly unregistered.
2804 // We do it automatically when the remote endpoint is closed so don't warn
2805 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002806 const bool stillHaveWindowHandle =
2807 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2808 nullptr;
2809 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 if (notify) {
2811 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 "events=0x%x",
2813 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 }
2815 }
2816
2817 // Unregister the channel.
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05002818 d->unregisterInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821}
2822
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002825 for (const auto& pair : mConnectionsByFd) {
2826 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
2828}
2829
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002831 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002832 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2833 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2834}
2835
2836void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2837 const CancelationOptions& options,
2838 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2839 for (const auto& it : monitorsByDisplay) {
2840 const std::vector<Monitor>& monitors = it.second;
2841 for (const Monitor& monitor : monitors) {
2842 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002843 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002844 }
2845}
2846
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002848 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002849 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002850 if (connection == nullptr) {
2851 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002853
2854 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855}
2856
2857void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2858 const sp<Connection>& connection, const CancelationOptions& options) {
2859 if (connection->status == Connection::STATUS_BROKEN) {
2860 return;
2861 }
2862
2863 nsecs_t currentTime = now();
2864
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002865 std::vector<EventEntry*> cancelationEvents =
2866 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002868 if (cancelationEvents.empty()) {
2869 return;
2870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002872 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2873 "with reality: %s, mode=%d.",
2874 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2875 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002877
2878 InputTarget target;
2879 sp<InputWindowHandle> windowHandle =
2880 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2881 if (windowHandle != nullptr) {
2882 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002883 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002884 target.globalScaleFactor = windowInfo->globalScaleFactor;
2885 }
2886 target.inputChannel = connection->inputChannel;
2887 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2888
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002889 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2890 EventEntry* cancelationEventEntry = cancelationEvents[i];
2891 switch (cancelationEventEntry->type) {
2892 case EventEntry::Type::KEY: {
2893 logOutboundKeyDetails("cancel - ",
2894 static_cast<const KeyEntry&>(*cancelationEventEntry));
2895 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002897 case EventEntry::Type::MOTION: {
2898 logOutboundMotionDetails("cancel - ",
2899 static_cast<const MotionEntry&>(*cancelationEventEntry));
2900 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002902 case EventEntry::Type::FOCUS: {
2903 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2904 break;
2905 }
2906 case EventEntry::Type::CONFIGURATION_CHANGED:
2907 case EventEntry::Type::DEVICE_RESET: {
2908 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2909 EventEntry::typeToString(cancelationEventEntry->type));
2910 break;
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
2913
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002914 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2915 target, InputTarget::FLAG_DISPATCH_AS_IS);
2916
2917 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002919
2920 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921}
2922
Svet Ganov5d3bc372020-01-26 23:11:07 -08002923void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2924 const sp<Connection>& connection) {
2925 if (connection->status == Connection::STATUS_BROKEN) {
2926 return;
2927 }
2928
2929 nsecs_t currentTime = now();
2930
2931 std::vector<EventEntry*> downEvents =
2932 connection->inputState.synthesizePointerDownEvents(currentTime);
2933
2934 if (downEvents.empty()) {
2935 return;
2936 }
2937
2938#if DEBUG_OUTBOUND_EVENT_DETAILS
2939 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2940 connection->getInputChannelName().c_str(), downEvents.size());
2941#endif
2942
2943 InputTarget target;
2944 sp<InputWindowHandle> windowHandle =
2945 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2946 if (windowHandle != nullptr) {
2947 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002948 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002949 target.globalScaleFactor = windowInfo->globalScaleFactor;
2950 }
2951 target.inputChannel = connection->inputChannel;
2952 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2953
2954 for (EventEntry* downEventEntry : downEvents) {
2955 switch (downEventEntry->type) {
2956 case EventEntry::Type::MOTION: {
2957 logOutboundMotionDetails("down - ",
2958 static_cast<const MotionEntry&>(*downEventEntry));
2959 break;
2960 }
2961
2962 case EventEntry::Type::KEY:
2963 case EventEntry::Type::FOCUS:
2964 case EventEntry::Type::CONFIGURATION_CHANGED:
2965 case EventEntry::Type::DEVICE_RESET: {
2966 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2967 EventEntry::typeToString(downEventEntry->type));
2968 break;
2969 }
2970 }
2971
2972 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2973 target, InputTarget::FLAG_DISPATCH_AS_IS);
2974
2975 downEventEntry->release();
2976 }
2977
2978 startDispatchCycleLocked(currentTime, connection);
2979}
2980
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002981MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002982 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 ALOG_ASSERT(pointerIds.value != 0);
2984
2985 uint32_t splitPointerIndexMap[MAX_POINTERS];
2986 PointerProperties splitPointerProperties[MAX_POINTERS];
2987 PointerCoords splitPointerCoords[MAX_POINTERS];
2988
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 uint32_t splitPointerCount = 0;
2991
2992 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 uint32_t pointerId = uint32_t(pointerProperties.id);
2997 if (pointerIds.hasBit(pointerId)) {
2998 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2999 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3000 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003001 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 splitPointerCount += 1;
3003 }
3004 }
3005
3006 if (splitPointerCount != pointerIds.count()) {
3007 // This is bad. We are missing some of the pointers that we expected to deliver.
3008 // Most likely this indicates that we received an ACTION_MOVE events that has
3009 // different pointer ids than we expected based on the previous ACTION_DOWN
3010 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3011 // in this way.
3012 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 "we expected there to be %d pointers. This probably means we received "
3014 "a broken sequence of pointer ids from the input device.",
3015 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003016 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 }
3018
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003019 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3022 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3024 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003025 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 uint32_t pointerId = uint32_t(pointerProperties.id);
3027 if (pointerIds.hasBit(pointerId)) {
3028 if (pointerIds.count() == 1) {
3029 // The first/last pointer went down/up.
3030 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003031 ? AMOTION_EVENT_ACTION_DOWN
3032 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 } else {
3034 // A secondary pointer went down/up.
3035 uint32_t splitPointerIndex = 0;
3036 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3037 splitPointerIndex += 1;
3038 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 action = maskedAction |
3040 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 }
3042 } else {
3043 // An unrelated pointer changed.
3044 action = AMOTION_EVENT_ACTION_MOVE;
3045 }
3046 }
3047
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003048 int32_t newId = mIdGenerator.nextId();
3049 if (ATRACE_ENABLED()) {
3050 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3051 ") to MotionEvent(id=0x%" PRIx32 ").",
3052 originalMotionEntry.id, newId);
3053 ATRACE_NAME(message.c_str());
3054 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003055 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003056 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3057 originalMotionEntry.source, originalMotionEntry.displayId,
3058 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003059 originalMotionEntry.actionButton, originalMotionEntry.flags,
3060 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3061 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3062 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3063 originalMotionEntry.xCursorPosition,
3064 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003065 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003067 if (originalMotionEntry.injectionState) {
3068 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 splitMotionEntry->injectionState->refCount += 1;
3070 }
3071
3072 return splitMotionEntry;
3073}
3074
3075void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3076#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003077 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078#endif
3079
3080 bool needWake;
3081 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003082 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083
Prabir Pradhan42611e02018-11-27 14:04:02 -08003084 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003085 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 needWake = enqueueInboundEventLocked(newEntry);
3087 } // release lock
3088
3089 if (needWake) {
3090 mLooper->wake();
3091 }
3092}
3093
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003094/**
3095 * If one of the meta shortcuts is detected, process them here:
3096 * Meta + Backspace -> generate BACK
3097 * Meta + Enter -> generate HOME
3098 * This will potentially overwrite keyCode and metaState.
3099 */
3100void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003102 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3103 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3104 if (keyCode == AKEYCODE_DEL) {
3105 newKeyCode = AKEYCODE_BACK;
3106 } else if (keyCode == AKEYCODE_ENTER) {
3107 newKeyCode = AKEYCODE_HOME;
3108 }
3109 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003110 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003111 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003112 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003113 keyCode = newKeyCode;
3114 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3115 }
3116 } else if (action == AKEY_EVENT_ACTION_UP) {
3117 // In order to maintain a consistent stream of up and down events, check to see if the key
3118 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3119 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003120 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003121 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003122 auto replacementIt = mReplacedKeys.find(replacement);
3123 if (replacementIt != mReplacedKeys.end()) {
3124 keyCode = replacementIt->second;
3125 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003126 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3127 }
3128 }
3129}
3130
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3132#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3134 "policyFlags=0x%x, action=0x%x, "
3135 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3136 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3137 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3138 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139#endif
3140 if (!validateKeyEvent(args->action)) {
3141 return;
3142 }
3143
3144 uint32_t policyFlags = args->policyFlags;
3145 int32_t flags = args->flags;
3146 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003147 // InputDispatcher tracks and generates key repeats on behalf of
3148 // whatever notifies it, so repeatCount should always be set to 0
3149 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3151 policyFlags |= POLICY_FLAG_VIRTUAL;
3152 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 if (policyFlags & POLICY_FLAG_FUNCTION) {
3155 metaState |= AMETA_FUNCTION_ON;
3156 }
3157
3158 policyFlags |= POLICY_FLAG_TRUSTED;
3159
Michael Wright78f24442014-08-06 15:55:28 -07003160 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003161 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003162
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003164 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003165 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3166 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
Michael Wright2b3c3302018-03-02 17:19:13 +00003168 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003170 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3171 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 bool needWake;
3176 { // acquire lock
3177 mLock.lock();
3178
3179 if (shouldSendKeyToInputFilterLocked(args)) {
3180 mLock.unlock();
3181
3182 policyFlags |= POLICY_FLAG_FILTERED;
3183 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3184 return; // event was consumed by the filter
3185 }
3186
3187 mLock.lock();
3188 }
3189
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003191 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 args->displayId, policyFlags, args->action, flags, keyCode,
3193 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
3195 needWake = enqueueInboundEventLocked(newEntry);
3196 mLock.unlock();
3197 } // release lock
3198
3199 if (needWake) {
3200 mLooper->wake();
3201 }
3202}
3203
3204bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3205 return mInputFilterEnabled;
3206}
3207
3208void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3209#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003210 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3211 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003212 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3213 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003214 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003215 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3216 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3217 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3218 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 for (uint32_t i = 0; i < args->pointerCount; i++) {
3220 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 "x=%f, y=%f, pressure=%f, size=%f, "
3222 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3223 "orientation=%f",
3224 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3225 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3226 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3227 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3228 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3229 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3230 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3231 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3232 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3233 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
3235#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3237 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 return;
3239 }
3240
3241 uint32_t policyFlags = args->policyFlags;
3242 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003243
3244 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003245 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003246 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3247 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250
3251 bool needWake;
3252 { // acquire lock
3253 mLock.lock();
3254
3255 if (shouldSendMotionToInputFilterLocked(args)) {
3256 mLock.unlock();
3257
3258 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003259 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003260 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3261 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003262 args->metaState, args->buttonState, args->classification, transform,
3263 args->xPrecision, args->yPrecision, args->xCursorPosition,
3264 args->yCursorPosition, args->downTime, args->eventTime,
3265 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266
3267 policyFlags |= POLICY_FLAG_FILTERED;
3268 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3269 return; // event was consumed by the filter
3270 }
3271
3272 mLock.lock();
3273 }
3274
3275 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003276 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003277 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003278 args->displayId, policyFlags, args->action, args->actionButton,
3279 args->flags, args->metaState, args->buttonState,
3280 args->classification, args->edgeFlags, args->xPrecision,
3281 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3282 args->downTime, args->pointerCount, args->pointerProperties,
3283 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
3285 needWake = enqueueInboundEventLocked(newEntry);
3286 mLock.unlock();
3287 } // release lock
3288
3289 if (needWake) {
3290 mLooper->wake();
3291 }
3292}
3293
3294bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003295 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296}
3297
3298void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3299#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003300 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 "switchMask=0x%08x",
3302 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303#endif
3304
3305 uint32_t policyFlags = args->policyFlags;
3306 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308}
3309
3310void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3311#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3313 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314#endif
3315
3316 bool needWake;
3317 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
Prabir Pradhan42611e02018-11-27 14:04:02 -08003320 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003321 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 needWake = enqueueInboundEventLocked(newEntry);
3323 } // release lock
3324
3325 if (needWake) {
3326 mLooper->wake();
3327 }
3328}
3329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3331 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003332 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333#if DEBUG_INBOUND_EVENT_DETAILS
3334 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003335 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3336 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003338 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339
3340 policyFlags |= POLICY_FLAG_INJECTED;
3341 if (hasInjectionPermission(injectorPid, injectorUid)) {
3342 policyFlags |= POLICY_FLAG_TRUSTED;
3343 }
3344
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003345 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003348 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3349 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 if (!validateKeyEvent(action)) {
3351 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003354 int32_t flags = incomingKey.getFlags();
3355 int32_t keyCode = incomingKey.getKeyCode();
3356 int32_t metaState = incomingKey.getMetaState();
3357 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003359 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003360 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003361 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3362 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3363 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3366 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003367 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368
3369 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3370 android::base::Timer t;
3371 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3372 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3373 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3374 std::to_string(t.duration().count()).c_str());
3375 }
3376 }
3377
3378 mLock.lock();
3379 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003380 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3381 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003382 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3383 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003384 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 injectedEntries.push(injectedEntry);
3386 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
3388
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 case AINPUT_EVENT_TYPE_MOTION: {
3390 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3391 int32_t action = motionEvent->getAction();
3392 size_t pointerCount = motionEvent->getPointerCount();
3393 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3394 int32_t actionButton = motionEvent->getActionButton();
3395 int32_t displayId = motionEvent->getDisplayId();
3396 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3397 return INPUT_EVENT_INJECTION_FAILED;
3398 }
3399
3400 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3401 nsecs_t eventTime = motionEvent->getEventTime();
3402 android::base::Timer t;
3403 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3404 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3405 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3406 std::to_string(t.duration().count()).c_str());
3407 }
3408 }
3409
3410 mLock.lock();
3411 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3412 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3413 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003414 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3415 motionEvent->getSource(), motionEvent->getDisplayId(),
3416 policyFlags, action, actionButton, motionEvent->getFlags(),
3417 motionEvent->getMetaState(), motionEvent->getButtonState(),
3418 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3419 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003420 motionEvent->getRawXCursorPosition(),
3421 motionEvent->getRawYCursorPosition(),
3422 motionEvent->getDownTime(), uint32_t(pointerCount),
3423 pointerProperties, samplePointerCoords,
3424 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 injectedEntries.push(injectedEntry);
3426 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3427 sampleEventTimes += 1;
3428 samplePointerCoords += pointerCount;
3429 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003430 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003431 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 motionEvent->getDisplayId(), policyFlags, action,
3433 actionButton, motionEvent->getFlags(),
3434 motionEvent->getMetaState(), motionEvent->getButtonState(),
3435 motionEvent->getClassification(),
3436 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3437 motionEvent->getYPrecision(),
3438 motionEvent->getRawXCursorPosition(),
3439 motionEvent->getRawYCursorPosition(),
3440 motionEvent->getDownTime(), uint32_t(pointerCount),
3441 pointerProperties, samplePointerCoords,
3442 motionEvent->getXOffset(), motionEvent->getYOffset());
3443 injectedEntries.push(nextInjectedEntry);
3444 }
3445 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003449 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452
3453 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3454 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3455 injectionState->injectionIsAsync = true;
3456 }
3457
3458 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003459 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
3461 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003462 while (!injectedEntries.empty()) {
3463 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3464 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 }
3466
3467 mLock.unlock();
3468
3469 if (needWake) {
3470 mLooper->wake();
3471 }
3472
3473 int32_t injectionResult;
3474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003475 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
3477 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3478 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3479 } else {
3480 for (;;) {
3481 injectionResult = injectionState->injectionResult;
3482 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3483 break;
3484 }
3485
3486 nsecs_t remainingTimeout = endTime - now();
3487 if (remainingTimeout <= 0) {
3488#if DEBUG_INJECTION
3489 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491#endif
3492 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3493 break;
3494 }
3495
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003496 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
3498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3500 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 while (injectionState->pendingForegroundDispatches != 0) {
3502#if DEBUG_INJECTION
3503 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505#endif
3506 nsecs_t remainingTimeout = endTime - now();
3507 if (remainingTimeout <= 0) {
3508#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003509 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3510 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511#endif
3512 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3513 break;
3514 }
3515
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003516 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518 }
3519 }
3520
3521 injectionState->release();
3522 } // release lock
3523
3524#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003525 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527#endif
3528
3529 return injectionResult;
3530}
3531
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003532std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003533 std::array<uint8_t, 32> calculatedHmac;
3534 std::unique_ptr<VerifiedInputEvent> result;
3535 switch (event.getType()) {
3536 case AINPUT_EVENT_TYPE_KEY: {
3537 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3538 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3539 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003540 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003541 break;
3542 }
3543 case AINPUT_EVENT_TYPE_MOTION: {
3544 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3545 VerifiedMotionEvent verifiedMotionEvent =
3546 verifiedMotionEventFromMotionEvent(motionEvent);
3547 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003548 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003549 break;
3550 }
3551 default: {
3552 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3553 return nullptr;
3554 }
3555 }
3556 if (calculatedHmac == INVALID_HMAC) {
3557 return nullptr;
3558 }
3559 if (calculatedHmac != event.getHmac()) {
3560 return nullptr;
3561 }
3562 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003563}
3564
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003566 return injectorUid == 0 ||
3567 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568}
3569
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003570void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 InjectionState* injectionState = entry->injectionState;
3572 if (injectionState) {
3573#if DEBUG_INJECTION
3574 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575 "injectorPid=%d, injectorUid=%d",
3576 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577#endif
3578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 // Log the outcome since the injector did not wait for the injection result.
3581 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 case INPUT_EVENT_INJECTION_SUCCEEDED:
3583 ALOGV("Asynchronous input event injection succeeded.");
3584 break;
3585 case INPUT_EVENT_INJECTION_FAILED:
3586 ALOGW("Asynchronous input event injection failed.");
3587 break;
3588 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3589 ALOGW("Asynchronous input event injection permission denied.");
3590 break;
3591 case INPUT_EVENT_INJECTION_TIMED_OUT:
3592 ALOGW("Asynchronous input event injection timed out.");
3593 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595 }
3596
3597 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003598 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
3600}
3601
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003602void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 InjectionState* injectionState = entry->injectionState;
3604 if (injectionState) {
3605 injectionState->pendingForegroundDispatches += 1;
3606 }
3607}
3608
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003609void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 InjectionState* injectionState = entry->injectionState;
3611 if (injectionState) {
3612 injectionState->pendingForegroundDispatches -= 1;
3613
3614 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003615 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617 }
3618}
3619
Vishnu Nairad321cd2020-08-20 16:40:21 -07003620const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003621 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003622 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3623 auto it = mWindowHandlesByDisplay.find(displayId);
3624 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003625}
3626
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003628 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003629 if (windowHandleToken == nullptr) {
3630 return nullptr;
3631 }
3632
Arthur Hungb92218b2018-08-14 12:00:21 +08003633 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003634 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003635 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003636 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003637 return windowHandle;
3638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
3640 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003641 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642}
3643
Vishnu Nairad321cd2020-08-20 16:40:21 -07003644sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3645 int displayId) const {
3646 if (windowHandleToken == nullptr) {
3647 return nullptr;
3648 }
3649
3650 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3651 if (windowHandle->getToken() == windowHandleToken) {
3652 return windowHandle;
3653 }
3654 }
3655 return nullptr;
3656}
3657
3658sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3659 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3660 return getWindowHandleLocked(focusedToken, displayId);
3661}
3662
Mady Mellor017bcd12020-06-23 19:12:00 +00003663bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3664 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003665 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003666 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003667 if (handle->getId() == windowHandle->getId() &&
3668 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003669 if (windowHandle->getInfo()->displayId != it.first) {
3670 ALOGE("Found window %s in display %" PRId32
3671 ", but it should belong to display %" PRId32,
3672 windowHandle->getName().c_str(), it.first,
3673 windowHandle->getInfo()->displayId);
3674 }
3675 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678 }
3679 return false;
3680}
3681
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003682bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3683 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3684 const bool noInputChannel =
3685 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3686 if (connection != nullptr && noInputChannel) {
3687 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3688 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3689 return false;
3690 }
3691
3692 if (connection == nullptr) {
3693 if (!noInputChannel) {
3694 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3695 }
3696 return false;
3697 }
3698 if (!connection->responsive) {
3699 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3700 return false;
3701 }
3702 return true;
3703}
3704
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003705std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3706 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003707 size_t count = mInputChannelsByToken.count(token);
3708 if (count == 0) {
3709 return nullptr;
3710 }
3711 return mInputChannelsByToken.at(token);
3712}
3713
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003714void InputDispatcher::updateWindowHandlesForDisplayLocked(
3715 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3716 if (inputWindowHandles.empty()) {
3717 // Remove all handles on a display if there are no windows left.
3718 mWindowHandlesByDisplay.erase(displayId);
3719 return;
3720 }
3721
3722 // Since we compare the pointer of input window handles across window updates, we need
3723 // to make sure the handle object for the same window stays unchanged across updates.
3724 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003725 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003726 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003727 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003728 }
3729
3730 std::vector<sp<InputWindowHandle>> newHandles;
3731 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3732 if (!handle->updateInfo()) {
3733 // handle no longer valid
3734 continue;
3735 }
3736
3737 const InputWindowInfo* info = handle->getInfo();
3738 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3739 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3740 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003741 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3742 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3743 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003744 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003745 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003746 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003747 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003748 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003749 }
3750
3751 if (info->displayId != displayId) {
3752 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3753 handle->getName().c_str(), displayId, info->displayId);
3754 continue;
3755 }
3756
Robert Carredd13602020-04-13 17:24:34 -07003757 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3758 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003759 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003760 oldHandle->updateFrom(handle);
3761 newHandles.push_back(oldHandle);
3762 } else {
3763 newHandles.push_back(handle);
3764 }
3765 }
3766
3767 // Insert or replace
3768 mWindowHandlesByDisplay[displayId] = newHandles;
3769}
3770
Arthur Hung72d8dc32020-03-28 00:48:39 +00003771void InputDispatcher::setInputWindows(
3772 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3773 { // acquire lock
3774 std::scoped_lock _l(mLock);
3775 for (auto const& i : handlesPerDisplay) {
3776 setInputWindowsLocked(i.second, i.first);
3777 }
3778 }
3779 // Wake up poll loop since it may need to make new input dispatching choices.
3780 mLooper->wake();
3781}
3782
Arthur Hungb92218b2018-08-14 12:00:21 +08003783/**
3784 * Called from InputManagerService, update window handle list by displayId that can receive input.
3785 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3786 * If set an empty list, remove all handles from the specific display.
3787 * For focused handle, check if need to change and send a cancel event to previous one.
3788 * For removed handle, check if need to send a cancel event if already in touch.
3789 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790void InputDispatcher::setInputWindowsLocked(
3791 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003792 if (DEBUG_FOCUS) {
3793 std::string windowList;
3794 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3795 windowList += iwh->getName() + " ";
3796 }
3797 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003800 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3801 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3802 const bool noInputWindow =
3803 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3804 if (noInputWindow && window->getToken() != nullptr) {
3805 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3806 window->getName().c_str());
3807 window->releaseChannel();
3808 }
3809 }
3810
Arthur Hung72d8dc32020-03-28 00:48:39 +00003811 // Copy old handles for release if they are no longer present.
3812 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813
Arthur Hung72d8dc32020-03-28 00:48:39 +00003814 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003815
Vishnu Nair958da932020-08-21 17:12:37 -07003816 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3817 if (mLastHoverWindowHandle &&
3818 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3819 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003820 mLastHoverWindowHandle = nullptr;
3821 }
3822
Vishnu Nair958da932020-08-21 17:12:37 -07003823 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3824 if (focusedToken) {
3825 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3826 if (result != FocusResult::OK) {
3827 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3828 }
3829 }
3830
3831 std::optional<FocusRequest> focusRequest =
3832 getOptionalValueByKey(mPendingFocusRequests, displayId);
3833 if (focusRequest) {
3834 // If the window from the pending request is now visible, provide it focus.
3835 FocusResult result = handleFocusRequestLocked(*focusRequest);
3836 if (result != FocusResult::NOT_VISIBLE) {
3837 // Drop the request if we were able to change the focus or we cannot change
3838 // it for another reason.
3839 mPendingFocusRequests.erase(displayId);
3840 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003843 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3844 mTouchStatesByDisplay.find(displayId);
3845 if (stateIt != mTouchStatesByDisplay.end()) {
3846 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003847 for (size_t i = 0; i < state.windows.size();) {
3848 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003849 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003850 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003851 ALOGD("Touched window was removed: %s in display %" PRId32,
3852 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003853 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003854 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003855 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3856 if (touchedInputChannel != nullptr) {
3857 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3858 "touched window was removed");
3859 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003861 state.windows.erase(state.windows.begin() + i);
3862 } else {
3863 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 }
3865 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003866 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003867
Arthur Hung72d8dc32020-03-28 00:48:39 +00003868 // Release information for windows that are no longer present.
3869 // This ensures that unused input channels are released promptly.
3870 // Otherwise, they might stick around until the window handle is destroyed
3871 // which might not happen until the next GC.
3872 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003873 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003874 if (DEBUG_FOCUS) {
3875 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003876 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003877 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003878 }
chaviw291d88a2019-02-14 10:33:58 -08003879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880}
3881
3882void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003883 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003884 if (DEBUG_FOCUS) {
3885 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3886 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3887 }
Chris Yea209fde2020-07-22 13:54:51 -07003888 if (inputApplicationHandle != nullptr &&
3889 inputApplicationHandle->getApplicationToken() != nullptr) {
3890 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Chris Yea209fde2020-07-22 13:54:51 -07003893 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003894 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003895
Chris Yea209fde2020-07-22 13:54:51 -07003896 // If oldFocusedApplicationHandle already exists
3897 if (oldFocusedApplicationHandle != nullptr) {
3898 // If a new focused application handle is different from the old one and
3899 // old focus application info is awaited focused application info.
3900 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3901 mAwaitedFocusedApplication != nullptr &&
3902 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3903 resetNoFocusedWindowTimeoutLocked();
3904 }
3905 // Erase the old application from container first
3906 mFocusedApplicationHandlesByDisplay.erase(displayId);
3907 // Should already get freed after removed from container but just double check.
3908 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003909 }
3910
Chris Yea209fde2020-07-22 13:54:51 -07003911 // Set the new application handle.
3912 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 } // release lock
3914
3915 // Wake up poll loop since it may need to make new input dispatching choices.
3916 mLooper->wake();
3917}
3918
Tiger Huang721e26f2018-07-24 22:26:19 +08003919/**
3920 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3921 * the display not specified.
3922 *
3923 * We track any unreleased events for each window. If a window loses the ability to receive the
3924 * released event, we will send a cancel event to it. So when the focused display is changed, we
3925 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3926 * display. The display-specified events won't be affected.
3927 */
3928void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003929 if (DEBUG_FOCUS) {
3930 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3931 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003932 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003933 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003934
3935 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003936 sp<IBinder> oldFocusedWindowToken =
3937 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3938 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003939 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003940 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003941 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003942 CancelationOptions
3943 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3944 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003945 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003946 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3947 }
3948 }
3949 mFocusedDisplayId = displayId;
3950
Chris Ye3c2d6f52020-08-09 10:39:48 -07003951 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003952 sp<IBinder> newFocusedWindowToken =
3953 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3954 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003955
Vishnu Nairad321cd2020-08-20 16:40:21 -07003956 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003957 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003958 if (!mFocusedWindowTokenByDisplay.empty()) {
3959 ALOGE("But another display has a focused window\n%s",
3960 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003961 }
3962 }
3963 }
3964
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003965 if (DEBUG_FOCUS) {
3966 logDispatchStateLocked();
3967 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003968 } // release lock
3969
3970 // Wake up poll loop since it may need to make new input dispatching choices.
3971 mLooper->wake();
3972}
3973
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003975 if (DEBUG_FOCUS) {
3976 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
3979 bool changed;
3980 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003981 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
3983 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3984 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003985 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987
3988 if (mDispatchEnabled && !enabled) {
3989 resetAndDropEverythingLocked("dispatcher is being disabled");
3990 }
3991
3992 mDispatchEnabled = enabled;
3993 mDispatchFrozen = frozen;
3994 changed = true;
3995 } else {
3996 changed = false;
3997 }
3998
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003999 if (DEBUG_FOCUS) {
4000 logDispatchStateLocked();
4001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 } // release lock
4003
4004 if (changed) {
4005 // Wake up poll loop since it may need to make new input dispatching choices.
4006 mLooper->wake();
4007 }
4008}
4009
4010void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
4012 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
4015 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004016 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017
4018 if (mInputFilterEnabled == enabled) {
4019 return;
4020 }
4021
4022 mInputFilterEnabled = enabled;
4023 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4024 } // release lock
4025
4026 // Wake up poll loop since there might be work to do to drop everything.
4027 mLooper->wake();
4028}
4029
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004030void InputDispatcher::setInTouchMode(bool inTouchMode) {
4031 std::scoped_lock lock(mLock);
4032 mInTouchMode = inTouchMode;
4033}
4034
chaviwfbe5d9c2018-12-26 12:23:37 -08004035bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4036 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004037 if (DEBUG_FOCUS) {
4038 ALOGD("Trivial transfer to same window.");
4039 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004040 return true;
4041 }
4042
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004044 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
chaviwfbe5d9c2018-12-26 12:23:37 -08004046 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4047 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004048 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004049 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 return false;
4051 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004052 if (DEBUG_FOCUS) {
4053 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4054 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004057 if (DEBUG_FOCUS) {
4058 ALOGD("Cannot transfer focus because windows are on different displays.");
4059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 return false;
4061 }
4062
4063 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004064 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4065 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004066 for (size_t i = 0; i < state.windows.size(); i++) {
4067 const TouchedWindow& touchedWindow = state.windows[i];
4068 if (touchedWindow.windowHandle == fromWindowHandle) {
4069 int32_t oldTargetFlags = touchedWindow.targetFlags;
4070 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004072 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 int32_t newTargetFlags = oldTargetFlags &
4075 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4076 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004077 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
Jeff Brownf086ddb2014-02-11 14:28:48 -08004079 found = true;
4080 goto Found;
4081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004084 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004087 if (DEBUG_FOCUS) {
4088 ALOGD("Focus transfer failed because from window did not have focus.");
4089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 return false;
4091 }
4092
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004093 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4094 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004095 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004096 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 CancelationOptions
4098 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4099 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004101 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004104 if (DEBUG_FOCUS) {
4105 logDispatchStateLocked();
4106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 } // release lock
4108
4109 // Wake up poll loop since it may need to make new input dispatching choices.
4110 mLooper->wake();
4111 return true;
4112}
4113
4114void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004115 if (DEBUG_FOCUS) {
4116 ALOGD("Resetting and dropping all events (%s).", reason);
4117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118
4119 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4120 synthesizeCancelationEventsForAllConnectionsLocked(options);
4121
4122 resetKeyRepeatLocked();
4123 releasePendingEventLocked();
4124 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004125 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004127 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004128 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004130 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131}
4132
4133void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004134 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 dumpDispatchStateLocked(dump);
4136
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004137 std::istringstream stream(dump);
4138 std::string line;
4139
4140 while (std::getline(stream, line, '\n')) {
4141 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143}
4144
Vishnu Nairad321cd2020-08-20 16:40:21 -07004145std::string InputDispatcher::dumpFocusedWindowsLocked() {
4146 if (mFocusedWindowTokenByDisplay.empty()) {
4147 return INDENT "FocusedWindows: <none>\n";
4148 }
4149
4150 std::string dump;
4151 dump += INDENT "FocusedWindows:\n";
4152 for (auto& it : mFocusedWindowTokenByDisplay) {
4153 const int32_t displayId = it.first;
4154 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4155 if (windowHandle) {
4156 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4157 windowHandle->getName().c_str());
4158 } else {
4159 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4160 " has focused token without a window'\n",
4161 displayId);
4162 }
4163 }
4164 return dump;
4165}
4166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004168 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4169 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4170 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004171 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Tiger Huang721e26f2018-07-24 22:26:19 +08004173 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4174 dump += StringPrintf(INDENT "FocusedApplications:\n");
4175 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4176 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004177 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004178 const std::chrono::duration timeout =
4179 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004181 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004182 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004185 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004187
Vishnu Nairad321cd2020-08-20 16:40:21 -07004188 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004190 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004192 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4193 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 state.displayId, toString(state.down), toString(state.split),
4196 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004197 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004199 for (size_t i = 0; i < state.windows.size(); i++) {
4200 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 dump += StringPrintf(INDENT4
4202 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4203 i, touchedWindow.windowHandle->getName().c_str(),
4204 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004205 }
4206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004208 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004209 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004210 dump += INDENT3 "Portal windows:\n";
4211 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004212 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4214 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004215 }
4216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 }
4218 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221
Arthur Hungb92218b2018-08-14 12:00:21 +08004222 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004224 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004225 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004226 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004227 dump += INDENT2 "Windows:\n";
4228 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004229 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004230 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Arthur Hungb92218b2018-08-14 12:00:21 +08004232 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004233 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4234 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004235 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004237 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 i, windowInfo->name.c_str(), windowInfo->displayId,
4239 windowInfo->portalToDisplayId,
4240 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004241 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 toString(windowInfo->hasWallpaper),
4243 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004244 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004245 static_cast<int32_t>(windowInfo->type),
4246 windowInfo->frameLeft, windowInfo->frameTop,
4247 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004248 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004249 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004250 dump += StringPrintf(", inputFeatures=%s",
4251 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004252 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4253 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004255 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004256 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004257 }
4258 } else {
4259 dump += INDENT2 "Windows: <none>\n";
4260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004263 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 }
4265
Michael Wright3dd60e22019-03-27 22:06:44 +00004266 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004268 const std::vector<Monitor>& monitors = it.second;
4269 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4270 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 }
4272 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004273 const std::vector<Monitor>& monitors = it.second;
4274 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4275 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004278 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280
4281 nsecs_t currentTime = now();
4282
4283 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004284 if (!mRecentQueue.empty()) {
4285 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4286 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004287 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004289 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 }
4294
4295 // Dump event currently being dispatched.
4296 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004297 dump += INDENT "PendingEvent:\n";
4298 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004300 dump += StringPrintf(", age=%" PRId64 "ms\n",
4301 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004303 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305
4306 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004307 if (!mInboundQueue.empty()) {
4308 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4309 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004312 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004315 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
4317
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004318 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004320 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4321 const KeyReplacement& replacement = pair.first;
4322 int32_t newKeyCode = pair.second;
4323 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004325 }
4326 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004327 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004328 }
4329
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004330 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004331 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004332 for (const auto& pair : mConnectionsByFd) {
4333 const sp<Connection>& connection = pair.second;
4334 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004335 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004336 pair.first, connection->getInputChannelName().c_str(),
4337 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004338 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004340 if (!connection->outboundQueue.empty()) {
4341 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4342 connection->outboundQueue.size());
4343 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 dump.append(INDENT4);
4345 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004346 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4347 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004349 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004352 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004355 if (!connection->waitQueue.empty()) {
4356 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4357 connection->waitQueue.size());
4358 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004359 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004361 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004362 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004364 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004365 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
4367 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004368 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
4370 }
4371 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004372 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374
4375 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004376 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4377 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
4381
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004382 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4384 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4385 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386}
4387
Michael Wright3dd60e22019-03-27 22:06:44 +00004388void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4389 const size_t numMonitors = monitors.size();
4390 for (size_t i = 0; i < numMonitors; i++) {
4391 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004392 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004393 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4394 dump += "\n";
4395 }
4396}
4397
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004398status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004400 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401#endif
4402
4403 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004404 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004405 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004406 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 return BAD_VALUE;
4410 }
4411
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004412 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413
4414 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004415 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004416 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4419 } // release lock
4420
4421 // Wake the looper because some connections have changed.
4422 mLooper->wake();
4423 return OK;
4424}
4425
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004426status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004427 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004428 { // acquire lock
4429 std::scoped_lock _l(mLock);
4430
4431 if (displayId < 0) {
4432 ALOGW("Attempted to register input monitor without a specified display.");
4433 return BAD_VALUE;
4434 }
4435
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004436 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 ALOGW("Attempted to register input monitor without an identifying token.");
4438 return BAD_VALUE;
4439 }
4440
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004441 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004442
4443 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004444 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004445 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004446
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004447 auto& monitorsByDisplay =
4448 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004449 monitorsByDisplay[displayId].emplace_back(inputChannel);
4450
4451 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 }
4453 // Wake the looper because some connections have changed.
4454 mLooper->wake();
4455 return OK;
4456}
4457
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004458status_t InputDispatcher::unregisterInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004460 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004462 status_t status = unregisterInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 if (status) {
4464 return status;
4465 }
4466 } // release lock
4467
4468 // Wake the poll loop because removing the connection may have changed the current
4469 // synchronization state.
4470 mLooper->wake();
4471 return OK;
4472}
4473
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004474status_t InputDispatcher::unregisterInputChannelLocked(const sp<IBinder>& connectionToken,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004476 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004477 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004478 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 return BAD_VALUE;
4480 }
4481
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004482 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004483 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004484
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004486 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004489 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490
4491 nsecs_t currentTime = now();
4492 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4493
4494 connection->status = Connection::STATUS_ZOMBIE;
4495 return OK;
4496}
4497
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004498void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4499 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4500 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004501}
4502
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004504 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004505 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004506 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004507 std::vector<Monitor>& monitors = it->second;
4508 const size_t numMonitors = monitors.size();
4509 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004510 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 monitors.erase(monitors.begin() + i);
4512 break;
4513 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004514 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004515 if (monitors.empty()) {
4516 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004517 } else {
4518 ++it;
4519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
4521}
4522
Michael Wright3dd60e22019-03-27 22:06:44 +00004523status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4524 { // acquire lock
4525 std::scoped_lock _l(mLock);
4526 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4527
4528 if (!foundDisplayId) {
4529 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4530 return BAD_VALUE;
4531 }
4532 int32_t displayId = foundDisplayId.value();
4533
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004534 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4535 mTouchStatesByDisplay.find(displayId);
4536 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004537 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4538 return BAD_VALUE;
4539 }
4540
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004541 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004542 std::optional<int32_t> foundDeviceId;
4543 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004544 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004545 foundDeviceId = state.deviceId;
4546 }
4547 }
4548 if (!foundDeviceId || !state.down) {
4549 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004551 return BAD_VALUE;
4552 }
4553 int32_t deviceId = foundDeviceId.value();
4554
4555 // Send cancel events to all the input channels we're stealing from.
4556 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004557 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004558 options.deviceId = deviceId;
4559 options.displayId = displayId;
4560 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004561 std::shared_ptr<InputChannel> channel =
4562 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004563 if (channel != nullptr) {
4564 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4565 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004566 }
4567 // Then clear the current touch state so we stop dispatching to them as well.
4568 state.filterNonMonitors();
4569 }
4570 return OK;
4571}
4572
Michael Wright3dd60e22019-03-27 22:06:44 +00004573std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4574 const sp<IBinder>& token) {
4575 for (const auto& it : mGestureMonitorsByDisplay) {
4576 const std::vector<Monitor>& monitors = it.second;
4577 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004578 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004579 return it.first;
4580 }
4581 }
4582 }
4583 return std::nullopt;
4584}
4585
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004586sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004587 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004588 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004589 }
4590
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004591 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004592 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004593 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004594 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 }
4596 }
Robert Carr4e670e52018-08-15 13:26:12 -07004597
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004598 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599}
4600
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004601void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004602 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004603 removeByValue(mConnectionsByFd, connection);
4604}
4605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4607 const sp<Connection>& connection, uint32_t seq,
4608 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004609 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4610 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 commandEntry->connection = connection;
4612 commandEntry->eventTime = currentTime;
4613 commandEntry->seq = seq;
4614 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004615 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616}
4617
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4619 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004623 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4624 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004626 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627}
4628
Vishnu Nairad321cd2020-08-20 16:40:21 -07004629void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4630 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004631 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4632 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004633 commandEntry->oldToken = oldToken;
4634 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004635 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004636}
4637
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004638void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4639 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4640 // is already healthy again. Don't raise ANR in this situation
4641 if (connection->waitQueue.empty()) {
4642 ALOGI("Not raising ANR because the connection %s has recovered",
4643 connection->inputChannel->getName().c_str());
4644 return;
4645 }
4646 /**
4647 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4648 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4649 * has changed. This could cause newer entries to time out before the already dispatched
4650 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4651 * processes the events linearly. So providing information about the oldest entry seems to be
4652 * most useful.
4653 */
4654 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4655 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4656 std::string reason =
4657 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4658 connection->inputChannel->getName().c_str(),
4659 ns2ms(currentWait),
4660 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004662 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4663 reason);
4664
4665 std::unique_ptr<CommandEntry> commandEntry =
4666 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4667 commandEntry->inputApplicationHandle = nullptr;
4668 commandEntry->inputChannel = connection->inputChannel;
4669 commandEntry->reason = std::move(reason);
4670 postCommandLocked(std::move(commandEntry));
4671}
4672
Chris Yea209fde2020-07-22 13:54:51 -07004673void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4675 application->getName().c_str());
4676
4677 updateLastAnrStateLocked(application, reason);
4678
4679 std::unique_ptr<CommandEntry> commandEntry =
4680 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4681 commandEntry->inputApplicationHandle = application;
4682 commandEntry->inputChannel = nullptr;
4683 commandEntry->reason = std::move(reason);
4684 postCommandLocked(std::move(commandEntry));
4685}
4686
4687void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4688 const std::string& reason) {
4689 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4690 updateLastAnrStateLocked(windowLabel, reason);
4691}
4692
Chris Yea209fde2020-07-22 13:54:51 -07004693void InputDispatcher::updateLastAnrStateLocked(
4694 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4696 updateLastAnrStateLocked(windowLabel, reason);
4697}
4698
4699void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4700 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004702 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 struct tm tm;
4704 localtime_r(&t, &tm);
4705 char timestr[64];
4706 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004707 mLastAnrState.clear();
4708 mLastAnrState += INDENT "ANR:\n";
4709 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4711 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004712 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713}
4714
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 mLock.unlock();
4717
4718 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4719
4720 mLock.lock();
4721}
4722
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 sp<Connection> connection = commandEntry->connection;
4725
4726 if (connection->status != Connection::STATUS_ZOMBIE) {
4727 mLock.unlock();
4728
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004729 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730
4731 mLock.lock();
4732 }
4733}
4734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004736 sp<IBinder> oldToken = commandEntry->oldToken;
4737 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004738 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004739 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004740 mLock.lock();
4741}
4742
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004743void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004744 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004745 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 mLock.unlock();
4747
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004748 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004749 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750
4751 mLock.lock();
4752
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004753 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4755 } else {
4756 // stop waking up for events in this connection, it is already not responding
4757 sp<Connection> connection = getConnectionLocked(token);
4758 if (connection == nullptr) {
4759 return;
4760 }
4761 cancelEventsForAnrLocked(connection);
4762 }
4763}
4764
Chris Yea209fde2020-07-22 13:54:51 -07004765void InputDispatcher::extendAnrTimeoutsLocked(
4766 const std::shared_ptr<InputApplicationHandle>& application,
4767 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768 sp<Connection> connection = getConnectionLocked(connectionToken);
4769 if (connection == nullptr) {
4770 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4771 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004772 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773 mAwaitedFocusedApplication = application;
4774 } else {
4775 // It's also possible that the connection already disappeared. No action necessary.
4776 }
4777 return;
4778 }
4779
4780 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004781 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004782
4783 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004784 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785 for (DispatchEntry* entry : connection->waitQueue) {
4786 if (newTimeout >= entry->timeoutTime) {
4787 // Already removed old entries when connection was marked unresponsive
4788 entry->timeoutTime = newTimeout;
4789 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4790 }
4791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792}
4793
4794void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4795 CommandEntry* commandEntry) {
4796 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004797 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798
4799 mLock.unlock();
4800
Michael Wright2b3c3302018-03-02 17:19:13 +00004801 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004803 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 : nullptr;
4805 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004806 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4807 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810
4811 mLock.lock();
4812
4813 if (delay < 0) {
4814 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4815 } else if (!delay) {
4816 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4817 } else {
4818 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4819 entry->interceptKeyWakeupTime = now() + delay;
4820 }
4821 entry->release();
4822}
4823
chaviwfd6d3512019-03-25 13:23:49 -07004824void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4825 mLock.unlock();
4826 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4827 mLock.lock();
4828}
4829
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830/**
4831 * Connection is responsive if it has no events in the waitQueue that are older than the
4832 * current time.
4833 */
4834static bool isConnectionResponsive(const Connection& connection) {
4835 const nsecs_t currentTime = now();
4836 for (const DispatchEntry* entry : connection.waitQueue) {
4837 if (entry->timeoutTime < currentTime) {
4838 return false;
4839 }
4840 }
4841 return true;
4842}
4843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004846 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004848 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849
4850 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004851 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004852 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004853 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004855 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004856 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004857 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004858 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4859 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004860 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004861 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004862
4863 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004864 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004865 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4866 restartEvent =
4867 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004868 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004869 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4870 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4871 handled);
4872 } else {
4873 restartEvent = false;
4874 }
4875
4876 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004877 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004878 // contents of the wait queue to have been drained, so we need to double-check
4879 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004880 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4881 if (dispatchEntryIt != connection->waitQueue.end()) {
4882 dispatchEntry = *dispatchEntryIt;
4883 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 mAnrTracker.erase(dispatchEntry->timeoutTime,
4885 connection->inputChannel->getConnectionToken());
4886 if (!connection->responsive) {
4887 connection->responsive = isConnectionResponsive(*connection);
4888 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004889 traceWaitQueueLength(connection);
4890 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004891 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004892 traceOutboundQueueLength(connection);
4893 } else {
4894 releaseDispatchEntry(dispatchEntry);
4895 }
4896 }
4897
4898 // Start the next dispatch cycle for this connection.
4899 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900}
4901
4902bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004903 DispatchEntry* dispatchEntry,
4904 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004905 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004906 if (!handled) {
4907 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004908 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004909 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004910 return false;
4911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004913 // Get the fallback key state.
4914 // Clear it out after dispatching the UP.
4915 int32_t originalKeyCode = keyEntry->keyCode;
4916 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4917 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4918 connection->inputState.removeFallbackKey(originalKeyCode);
4919 }
4920
4921 if (handled || !dispatchEntry->hasForegroundTarget()) {
4922 // If the application handles the original key for which we previously
4923 // generated a fallback or if the window is not a foreground window,
4924 // then cancel the associated fallback key, if any.
4925 if (fallbackKeyCode != -1) {
4926 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004928 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004929 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4930 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4931 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004933 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
4936 mLock.unlock();
4937
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004938 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004939 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940
4941 mLock.lock();
4942
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004943 // Cancel the fallback key.
4944 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004946 "application handled the original non-fallback key "
4947 "or is no longer a foreground target, "
4948 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 options.keyCode = fallbackKeyCode;
4950 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 connection->inputState.removeFallbackKey(originalKeyCode);
4953 }
4954 } else {
4955 // If the application did not handle a non-fallback key, first check
4956 // that we are in a good state to perform unhandled key event processing
4957 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004958 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004959 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004962 "since this is not an initial down. "
4963 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4964 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004966 return false;
4967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969 // Dispatch the unhandled key to the policy.
4970#if DEBUG_OUTBOUND_EVENT_DETAILS
4971 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004972 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4973 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004974#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004975 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004976
4977 mLock.unlock();
4978
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004979 bool fallback =
4980 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4981 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982
4983 mLock.lock();
4984
4985 if (connection->status != Connection::STATUS_NORMAL) {
4986 connection->inputState.removeFallbackKey(originalKeyCode);
4987 return false;
4988 }
4989
4990 // Latch the fallback keycode for this key on an initial down.
4991 // The fallback keycode cannot change at any other point in the lifecycle.
4992 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004994 fallbackKeyCode = event.getKeyCode();
4995 } else {
4996 fallbackKeyCode = AKEYCODE_UNKNOWN;
4997 }
4998 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4999 }
5000
5001 ALOG_ASSERT(fallbackKeyCode != -1);
5002
5003 // Cancel the fallback key if the policy decides not to send it anymore.
5004 // We will continue to dispatch the key to the policy but we will no
5005 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5007 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005008#if DEBUG_OUTBOUND_EVENT_DETAILS
5009 if (fallback) {
5010 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 "as a fallback for %d, but on the DOWN it had requested "
5012 "to send %d instead. Fallback canceled.",
5013 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005014 } else {
5015 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 "but on the DOWN it had requested to send %d. "
5017 "Fallback canceled.",
5018 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005019 }
5020#endif
5021
5022 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5023 "canceling fallback, policy no longer desires it");
5024 options.keyCode = fallbackKeyCode;
5025 synthesizeCancelationEventsForConnectionLocked(connection, options);
5026
5027 fallback = false;
5028 fallbackKeyCode = AKEYCODE_UNKNOWN;
5029 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005030 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005031 }
5032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
5034#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005035 {
5036 std::string msg;
5037 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5038 connection->inputState.getFallbackKeys();
5039 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005040 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005042 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005044 }
5045#endif
5046
5047 if (fallback) {
5048 // Restart the dispatch cycle using the fallback key.
5049 keyEntry->eventTime = event.getEventTime();
5050 keyEntry->deviceId = event.getDeviceId();
5051 keyEntry->source = event.getSource();
5052 keyEntry->displayId = event.getDisplayId();
5053 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5054 keyEntry->keyCode = fallbackKeyCode;
5055 keyEntry->scanCode = event.getScanCode();
5056 keyEntry->metaState = event.getMetaState();
5057 keyEntry->repeatCount = event.getRepeatCount();
5058 keyEntry->downTime = event.getDownTime();
5059 keyEntry->syntheticRepeat = false;
5060
5061#if DEBUG_OUTBOUND_EVENT_DETAILS
5062 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5064 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005065#endif
5066 return true; // restart the event
5067 } else {
5068#if DEBUG_OUTBOUND_EVENT_DETAILS
5069 ALOGD("Unhandled key event: No fallback key.");
5070#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005071
5072 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005073 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 }
5075 }
5076 return false;
5077}
5078
5079bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005080 DispatchEntry* dispatchEntry,
5081 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 return false;
5083}
5084
5085void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5086 mLock.unlock();
5087
5088 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5089
5090 mLock.lock();
5091}
5092
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005093KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5094 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005095 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005096 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5097 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005098 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099}
5100
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005101void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5102 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 // TODO Write some statistics about how long we spend waiting.
5104}
5105
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005106/**
5107 * Report the touch event latency to the statsd server.
5108 * Input events are reported for statistics if:
5109 * - This is a touchscreen event
5110 * - InputFilter is not enabled
5111 * - Event is not injected or synthesized
5112 *
5113 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5114 * from getting aggregated with the "old" data.
5115 */
5116void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5117 REQUIRES(mLock) {
5118 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5119 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5120 if (!reportForStatistics) {
5121 return;
5122 }
5123
5124 if (mTouchStatistics.shouldReport()) {
5125 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5126 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5127 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5128 mTouchStatistics.reset();
5129 }
5130 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5131 mTouchStatistics.addValue(latencyMicros);
5132}
5133
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134void InputDispatcher::traceInboundQueueLengthLocked() {
5135 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005136 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138}
5139
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005140void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 if (ATRACE_ENABLED()) {
5142 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005143 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005144 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146}
5147
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005148void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 if (ATRACE_ENABLED()) {
5150 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005151 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005152 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154}
5155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005156void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005157 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005159 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 dumpDispatchStateLocked(dump);
5161
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005162 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005163 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005164 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166}
5167
5168void InputDispatcher::monitor() {
5169 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005170 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005172 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173}
5174
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005175/**
5176 * Wake up the dispatcher and wait until it processes all events and commands.
5177 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5178 * this method can be safely called from any thread, as long as you've ensured that
5179 * the work you are interested in completing has already been queued.
5180 */
5181bool InputDispatcher::waitForIdle() {
5182 /**
5183 * Timeout should represent the longest possible time that a device might spend processing
5184 * events and commands.
5185 */
5186 constexpr std::chrono::duration TIMEOUT = 100ms;
5187 std::unique_lock lock(mLock);
5188 mLooper->wake();
5189 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5190 return result == std::cv_status::no_timeout;
5191}
5192
Vishnu Naire798b472020-07-23 13:52:21 -07005193/**
5194 * Sets focus to the window identified by the token. This must be called
5195 * after updating any input window handles.
5196 *
5197 * Params:
5198 * request.token - input channel token used to identify the window that should gain focus.
5199 * request.focusedToken - the token that the caller expects currently to be focused. If the
5200 * specified token does not match the currently focused window, this request will be dropped.
5201 * If the specified focused token matches the currently focused window, the call will succeed.
5202 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5203 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5204 * when requesting the focus change. This determines which request gets
5205 * precedence if there is a focus change request from another source such as pointer down.
5206 */
Vishnu Nair958da932020-08-21 17:12:37 -07005207void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5208 { // acquire lock
5209 std::scoped_lock _l(mLock);
5210
5211 const int32_t displayId = request.displayId;
5212 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5213 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5214 ALOGD_IF(DEBUG_FOCUS,
5215 "setFocusedWindow on display %" PRId32
5216 " ignored, reason: focusedToken is not focused",
5217 displayId);
5218 return;
5219 }
5220
5221 mPendingFocusRequests.erase(displayId);
5222 FocusResult result = handleFocusRequestLocked(request);
5223 if (result == FocusResult::NOT_VISIBLE) {
5224 // The requested window is not currently visible. Wait for the window to become visible
5225 // and then provide it focus. This is to handle situations where a user action triggers
5226 // a new window to appear. We want to be able to queue any key events after the user
5227 // action and deliver it to the newly focused window. In order for this to happen, we
5228 // take focus from the currently focused window so key events can be queued.
5229 ALOGD_IF(DEBUG_FOCUS,
5230 "setFocusedWindow on display %" PRId32
5231 " pending, reason: window is not visible",
5232 displayId);
5233 mPendingFocusRequests[displayId] = request;
5234 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5235 "setFocusedWindow_AwaitingWindowVisibility");
5236 } else if (result != FocusResult::OK) {
5237 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5238 typeToString(result));
5239 }
5240 } // release lock
5241 // Wake up poll loop since it may need to make new input dispatching choices.
5242 mLooper->wake();
5243}
5244
5245InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5246 const FocusRequest& request) {
5247 const int32_t displayId = request.displayId;
5248 const sp<IBinder> newFocusedToken = request.token;
5249 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5250
5251 if (oldFocusedToken == request.token) {
5252 ALOGD_IF(DEBUG_FOCUS,
5253 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5254 displayId);
5255 return FocusResult::OK;
5256 }
5257
5258 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5259 if (result != FocusResult::OK) {
5260 return result;
5261 }
5262
5263 std::string_view reason =
5264 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5265 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5266 return FocusResult::OK;
5267}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005268
Vishnu Nairad321cd2020-08-20 16:40:21 -07005269void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5270 const sp<IBinder>& newFocusedToken, int32_t displayId,
5271 std::string_view reason) {
5272 if (oldFocusedToken) {
5273 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005274 if (focusedInputChannel) {
5275 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5276 "focus left window");
5277 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005278 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005279 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005280 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005281 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005282 if (newFocusedToken) {
5283 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5284 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005285 }
5286
5287 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005288 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005289 }
5290}
Vishnu Nair958da932020-08-21 17:12:37 -07005291
5292/**
5293 * Checks if the window token can be focused on a display. The token can be focused if there is
5294 * at least one window handle that is visible with the same token and all window handles with the
5295 * same token are focusable.
5296 *
5297 * In the case of mirroring, two windows may share the same window token and their visibility
5298 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5299 * we expect the focusability of the windows to match since its hard to reason why one window can
5300 * receive focus events and the other cannot when both are backed by the same input channel.
5301 */
5302InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5303 int32_t displayId) const {
5304 bool allWindowsAreFocusable = true;
5305 bool visibleWindowFound = false;
5306 bool windowFound = false;
5307 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5308 if (window->getToken() != token) {
5309 continue;
5310 }
5311 windowFound = true;
5312 if (window->getInfo()->visible) {
5313 // Check if at least a single window is visible.
5314 visibleWindowFound = true;
5315 }
5316 if (!window->getInfo()->focusable) {
5317 // Check if all windows with the window token are focusable.
5318 allWindowsAreFocusable = false;
5319 break;
5320 }
5321 }
5322
5323 if (!windowFound) {
5324 return FocusResult::NO_WINDOW;
5325 }
5326 if (!allWindowsAreFocusable) {
5327 return FocusResult::NOT_FOCUSABLE;
5328 }
5329 if (!visibleWindowFound) {
5330 return FocusResult::NOT_VISIBLE;
5331 }
5332
5333 return FocusResult::OK;
5334}
Garfield Tane84e6f92019-08-29 17:28:41 -07005335} // namespace android::inputdispatcher