blob: 7b7249a7b8e3454a572a5dc4d6c69f59c100583f [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 Vishniakouce5ab082020-07-09 17:03:21 -0500404 unregisterInputChannel(*connection->inputChannel);
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 Vishniakouce5ab082020-07-09 17:03:21 -05002818 d->unregisterInputChannelLocked(*connection->inputChannel, 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
3338
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003339 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340
3341 policyFlags |= POLICY_FLAG_INJECTED;
3342 if (hasInjectionPermission(injectorPid, injectorUid)) {
3343 policyFlags |= POLICY_FLAG_TRUSTED;
3344 }
3345
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003346 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003349 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3350 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 if (!validateKeyEvent(action)) {
3352 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003355 int32_t flags = incomingKey.getFlags();
3356 int32_t keyCode = incomingKey.getKeyCode();
3357 int32_t metaState = incomingKey.getMetaState();
3358 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003360 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003361 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003362 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3363 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3364 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3367 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003368 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369
3370 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3371 android::base::Timer t;
3372 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3373 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3374 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3375 std::to_string(t.duration().count()).c_str());
3376 }
3377 }
3378
3379 mLock.lock();
3380 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003381 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3382 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003383 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3384 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003385 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 injectedEntries.push(injectedEntry);
3387 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 case AINPUT_EVENT_TYPE_MOTION: {
3391 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3392 int32_t action = motionEvent->getAction();
3393 size_t pointerCount = motionEvent->getPointerCount();
3394 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3395 int32_t actionButton = motionEvent->getActionButton();
3396 int32_t displayId = motionEvent->getDisplayId();
3397 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3398 return INPUT_EVENT_INJECTION_FAILED;
3399 }
3400
3401 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3402 nsecs_t eventTime = motionEvent->getEventTime();
3403 android::base::Timer t;
3404 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3405 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3406 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3407 std::to_string(t.duration().count()).c_str());
3408 }
3409 }
3410
3411 mLock.lock();
3412 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3413 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3414 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003415 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3416 motionEvent->getSource(), motionEvent->getDisplayId(),
3417 policyFlags, action, actionButton, motionEvent->getFlags(),
3418 motionEvent->getMetaState(), motionEvent->getButtonState(),
3419 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3420 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003421 motionEvent->getRawXCursorPosition(),
3422 motionEvent->getRawYCursorPosition(),
3423 motionEvent->getDownTime(), uint32_t(pointerCount),
3424 pointerProperties, samplePointerCoords,
3425 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003426 injectedEntries.push(injectedEntry);
3427 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3428 sampleEventTimes += 1;
3429 samplePointerCoords += pointerCount;
3430 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003431 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003432 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 motionEvent->getDisplayId(), policyFlags, action,
3434 actionButton, motionEvent->getFlags(),
3435 motionEvent->getMetaState(), motionEvent->getButtonState(),
3436 motionEvent->getClassification(),
3437 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3438 motionEvent->getYPrecision(),
3439 motionEvent->getRawXCursorPosition(),
3440 motionEvent->getRawYCursorPosition(),
3441 motionEvent->getDownTime(), uint32_t(pointerCount),
3442 pointerProperties, samplePointerCoords,
3443 motionEvent->getXOffset(), motionEvent->getYOffset());
3444 injectedEntries.push(nextInjectedEntry);
3445 }
3446 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003450 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 }
3453
3454 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3455 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3456 injectionState->injectionIsAsync = true;
3457 }
3458
3459 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003460 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
3462 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003463 while (!injectedEntries.empty()) {
3464 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3465 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 }
3467
3468 mLock.unlock();
3469
3470 if (needWake) {
3471 mLooper->wake();
3472 }
3473
3474 int32_t injectionResult;
3475 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003476 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477
3478 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3479 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3480 } else {
3481 for (;;) {
3482 injectionResult = injectionState->injectionResult;
3483 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3484 break;
3485 }
3486
3487 nsecs_t remainingTimeout = endTime - now();
3488 if (remainingTimeout <= 0) {
3489#if DEBUG_INJECTION
3490 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492#endif
3493 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3494 break;
3495 }
3496
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003497 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 }
3499
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3501 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 while (injectionState->pendingForegroundDispatches != 0) {
3503#if DEBUG_INJECTION
3504 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506#endif
3507 nsecs_t remainingTimeout = endTime - now();
3508 if (remainingTimeout <= 0) {
3509#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3511 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512#endif
3513 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3514 break;
3515 }
3516
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003517 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519 }
3520 }
3521
3522 injectionState->release();
3523 } // release lock
3524
3525#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003526 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528#endif
3529
3530 return injectionResult;
3531}
3532
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003533std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003534 std::array<uint8_t, 32> calculatedHmac;
3535 std::unique_ptr<VerifiedInputEvent> result;
3536 switch (event.getType()) {
3537 case AINPUT_EVENT_TYPE_KEY: {
3538 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3539 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3540 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003541 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003542 break;
3543 }
3544 case AINPUT_EVENT_TYPE_MOTION: {
3545 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3546 VerifiedMotionEvent verifiedMotionEvent =
3547 verifiedMotionEventFromMotionEvent(motionEvent);
3548 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003549 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003550 break;
3551 }
3552 default: {
3553 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3554 return nullptr;
3555 }
3556 }
3557 if (calculatedHmac == INVALID_HMAC) {
3558 return nullptr;
3559 }
3560 if (calculatedHmac != event.getHmac()) {
3561 return nullptr;
3562 }
3563 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003564}
3565
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003567 return injectorUid == 0 ||
3568 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569}
3570
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003571void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 InjectionState* injectionState = entry->injectionState;
3573 if (injectionState) {
3574#if DEBUG_INJECTION
3575 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 "injectorPid=%d, injectorUid=%d",
3577 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578#endif
3579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 // Log the outcome since the injector did not wait for the injection result.
3582 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003583 case INPUT_EVENT_INJECTION_SUCCEEDED:
3584 ALOGV("Asynchronous input event injection succeeded.");
3585 break;
3586 case INPUT_EVENT_INJECTION_FAILED:
3587 ALOGW("Asynchronous input event injection failed.");
3588 break;
3589 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3590 ALOGW("Asynchronous input event injection permission denied.");
3591 break;
3592 case INPUT_EVENT_INJECTION_TIMED_OUT:
3593 ALOGW("Asynchronous input event injection timed out.");
3594 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596 }
3597
3598 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003599 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
3601}
3602
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003603void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 InjectionState* injectionState = entry->injectionState;
3605 if (injectionState) {
3606 injectionState->pendingForegroundDispatches += 1;
3607 }
3608}
3609
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003610void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 InjectionState* injectionState = entry->injectionState;
3612 if (injectionState) {
3613 injectionState->pendingForegroundDispatches -= 1;
3614
3615 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003616 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618 }
3619}
3620
Vishnu Nairad321cd2020-08-20 16:40:21 -07003621const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003622 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003623 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3624 auto it = mWindowHandlesByDisplay.find(displayId);
3625 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003626}
3627
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003629 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003630 if (windowHandleToken == nullptr) {
3631 return nullptr;
3632 }
3633
Arthur Hungb92218b2018-08-14 12:00:21 +08003634 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003635 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003636 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003637 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003638 return windowHandle;
3639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
3641 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003642 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643}
3644
Vishnu Nairad321cd2020-08-20 16:40:21 -07003645sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3646 int displayId) const {
3647 if (windowHandleToken == nullptr) {
3648 return nullptr;
3649 }
3650
3651 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3652 if (windowHandle->getToken() == windowHandleToken) {
3653 return windowHandle;
3654 }
3655 }
3656 return nullptr;
3657}
3658
3659sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3660 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3661 return getWindowHandleLocked(focusedToken, displayId);
3662}
3663
Mady Mellor017bcd12020-06-23 19:12:00 +00003664bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3665 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003666 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003667 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003668 if (handle->getId() == windowHandle->getId() &&
3669 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003670 if (windowHandle->getInfo()->displayId != it.first) {
3671 ALOGE("Found window %s in display %" PRId32
3672 ", but it should belong to display %" PRId32,
3673 windowHandle->getName().c_str(), it.first,
3674 windowHandle->getInfo()->displayId);
3675 }
3676 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
3679 }
3680 return false;
3681}
3682
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003683bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3684 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3685 const bool noInputChannel =
3686 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3687 if (connection != nullptr && noInputChannel) {
3688 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3689 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3690 return false;
3691 }
3692
3693 if (connection == nullptr) {
3694 if (!noInputChannel) {
3695 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3696 }
3697 return false;
3698 }
3699 if (!connection->responsive) {
3700 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3701 return false;
3702 }
3703 return true;
3704}
3705
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003706std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3707 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003708 size_t count = mInputChannelsByToken.count(token);
3709 if (count == 0) {
3710 return nullptr;
3711 }
3712 return mInputChannelsByToken.at(token);
3713}
3714
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003715void InputDispatcher::updateWindowHandlesForDisplayLocked(
3716 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3717 if (inputWindowHandles.empty()) {
3718 // Remove all handles on a display if there are no windows left.
3719 mWindowHandlesByDisplay.erase(displayId);
3720 return;
3721 }
3722
3723 // Since we compare the pointer of input window handles across window updates, we need
3724 // to make sure the handle object for the same window stays unchanged across updates.
3725 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003726 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003727 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003728 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003729 }
3730
3731 std::vector<sp<InputWindowHandle>> newHandles;
3732 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3733 if (!handle->updateInfo()) {
3734 // handle no longer valid
3735 continue;
3736 }
3737
3738 const InputWindowInfo* info = handle->getInfo();
3739 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3740 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3741 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003742 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3743 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3744 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003745 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003746 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003747 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003748 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003749 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003750 }
3751
3752 if (info->displayId != displayId) {
3753 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3754 handle->getName().c_str(), displayId, info->displayId);
3755 continue;
3756 }
3757
Robert Carredd13602020-04-13 17:24:34 -07003758 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3759 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003760 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003761 oldHandle->updateFrom(handle);
3762 newHandles.push_back(oldHandle);
3763 } else {
3764 newHandles.push_back(handle);
3765 }
3766 }
3767
3768 // Insert or replace
3769 mWindowHandlesByDisplay[displayId] = newHandles;
3770}
3771
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772void InputDispatcher::setInputWindows(
3773 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3774 { // acquire lock
3775 std::scoped_lock _l(mLock);
3776 for (auto const& i : handlesPerDisplay) {
3777 setInputWindowsLocked(i.second, i.first);
3778 }
3779 }
3780 // Wake up poll loop since it may need to make new input dispatching choices.
3781 mLooper->wake();
3782}
3783
Arthur Hungb92218b2018-08-14 12:00:21 +08003784/**
3785 * Called from InputManagerService, update window handle list by displayId that can receive input.
3786 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3787 * If set an empty list, remove all handles from the specific display.
3788 * For focused handle, check if need to change and send a cancel event to previous one.
3789 * For removed handle, check if need to send a cancel event if already in touch.
3790 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003791void InputDispatcher::setInputWindowsLocked(
3792 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003793 if (DEBUG_FOCUS) {
3794 std::string windowList;
3795 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3796 windowList += iwh->getName() + " ";
3797 }
3798 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003801 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3802 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3803 const bool noInputWindow =
3804 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3805 if (noInputWindow && window->getToken() != nullptr) {
3806 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3807 window->getName().c_str());
3808 window->releaseChannel();
3809 }
3810 }
3811
Arthur Hung72d8dc32020-03-28 00:48:39 +00003812 // Copy old handles for release if they are no longer present.
3813 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814
Arthur Hung72d8dc32020-03-28 00:48:39 +00003815 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003816
Vishnu Nair958da932020-08-21 17:12:37 -07003817 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3818 if (mLastHoverWindowHandle &&
3819 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3820 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003821 mLastHoverWindowHandle = nullptr;
3822 }
3823
Vishnu Nair958da932020-08-21 17:12:37 -07003824 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3825 if (focusedToken) {
3826 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3827 if (result != FocusResult::OK) {
3828 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3829 }
3830 }
3831
3832 std::optional<FocusRequest> focusRequest =
3833 getOptionalValueByKey(mPendingFocusRequests, displayId);
3834 if (focusRequest) {
3835 // If the window from the pending request is now visible, provide it focus.
3836 FocusResult result = handleFocusRequestLocked(*focusRequest);
3837 if (result != FocusResult::NOT_VISIBLE) {
3838 // Drop the request if we were able to change the focus or we cannot change
3839 // it for another reason.
3840 mPendingFocusRequests.erase(displayId);
3841 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003844 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3845 mTouchStatesByDisplay.find(displayId);
3846 if (stateIt != mTouchStatesByDisplay.end()) {
3847 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003848 for (size_t i = 0; i < state.windows.size();) {
3849 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003850 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003851 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003852 ALOGD("Touched window was removed: %s in display %" PRId32,
3853 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003854 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003855 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003856 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3857 if (touchedInputChannel != nullptr) {
3858 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3859 "touched window was removed");
3860 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003862 state.windows.erase(state.windows.begin() + i);
3863 } else {
3864 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 }
3866 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003867 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003868
Arthur Hung72d8dc32020-03-28 00:48:39 +00003869 // Release information for windows that are no longer present.
3870 // This ensures that unused input channels are released promptly.
3871 // Otherwise, they might stick around until the window handle is destroyed
3872 // which might not happen until the next GC.
3873 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003874 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003875 if (DEBUG_FOCUS) {
3876 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003877 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003878 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003879 }
chaviw291d88a2019-02-14 10:33:58 -08003880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881}
3882
3883void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003884 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003885 if (DEBUG_FOCUS) {
3886 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3887 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3888 }
Chris Yea209fde2020-07-22 13:54:51 -07003889 if (inputApplicationHandle != nullptr &&
3890 inputApplicationHandle->getApplicationToken() != nullptr) {
3891 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003892 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893
Chris Yea209fde2020-07-22 13:54:51 -07003894 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003895 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003896
Chris Yea209fde2020-07-22 13:54:51 -07003897 // If oldFocusedApplicationHandle already exists
3898 if (oldFocusedApplicationHandle != nullptr) {
3899 // If a new focused application handle is different from the old one and
3900 // old focus application info is awaited focused application info.
3901 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3902 mAwaitedFocusedApplication != nullptr &&
3903 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3904 resetNoFocusedWindowTimeoutLocked();
3905 }
3906 // Erase the old application from container first
3907 mFocusedApplicationHandlesByDisplay.erase(displayId);
3908 // Should already get freed after removed from container but just double check.
3909 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003910 }
3911
Chris Yea209fde2020-07-22 13:54:51 -07003912 // Set the new application handle.
3913 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 } // release lock
3915
3916 // Wake up poll loop since it may need to make new input dispatching choices.
3917 mLooper->wake();
3918}
3919
Tiger Huang721e26f2018-07-24 22:26:19 +08003920/**
3921 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3922 * the display not specified.
3923 *
3924 * We track any unreleased events for each window. If a window loses the ability to receive the
3925 * released event, we will send a cancel event to it. So when the focused display is changed, we
3926 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3927 * display. The display-specified events won't be affected.
3928 */
3929void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003930 if (DEBUG_FOCUS) {
3931 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3932 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003933 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003934 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003935
3936 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003937 sp<IBinder> oldFocusedWindowToken =
3938 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3939 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003940 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003941 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003942 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943 CancelationOptions
3944 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3945 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003946 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003947 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3948 }
3949 }
3950 mFocusedDisplayId = displayId;
3951
Chris Ye3c2d6f52020-08-09 10:39:48 -07003952 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003953 sp<IBinder> newFocusedWindowToken =
3954 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3955 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003956
Vishnu Nairad321cd2020-08-20 16:40:21 -07003957 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003958 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003959 if (!mFocusedWindowTokenByDisplay.empty()) {
3960 ALOGE("But another display has a focused window\n%s",
3961 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003962 }
3963 }
3964 }
3965
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003966 if (DEBUG_FOCUS) {
3967 logDispatchStateLocked();
3968 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003969 } // release lock
3970
3971 // Wake up poll loop since it may need to make new input dispatching choices.
3972 mLooper->wake();
3973}
3974
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003976 if (DEBUG_FOCUS) {
3977 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
3980 bool changed;
3981 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003982 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
3984 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3985 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003986 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 }
3988
3989 if (mDispatchEnabled && !enabled) {
3990 resetAndDropEverythingLocked("dispatcher is being disabled");
3991 }
3992
3993 mDispatchEnabled = enabled;
3994 mDispatchFrozen = frozen;
3995 changed = true;
3996 } else {
3997 changed = false;
3998 }
3999
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004000 if (DEBUG_FOCUS) {
4001 logDispatchStateLocked();
4002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 } // release lock
4004
4005 if (changed) {
4006 // Wake up poll loop since it may need to make new input dispatching choices.
4007 mLooper->wake();
4008 }
4009}
4010
4011void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004012 if (DEBUG_FOCUS) {
4013 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015
4016 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004017 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
4019 if (mInputFilterEnabled == enabled) {
4020 return;
4021 }
4022
4023 mInputFilterEnabled = enabled;
4024 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4025 } // release lock
4026
4027 // Wake up poll loop since there might be work to do to drop everything.
4028 mLooper->wake();
4029}
4030
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004031void InputDispatcher::setInTouchMode(bool inTouchMode) {
4032 std::scoped_lock lock(mLock);
4033 mInTouchMode = inTouchMode;
4034}
4035
chaviwfbe5d9c2018-12-26 12:23:37 -08004036bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4037 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004038 if (DEBUG_FOCUS) {
4039 ALOGD("Trivial transfer to same window.");
4040 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004041 return true;
4042 }
4043
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
chaviwfbe5d9c2018-12-26 12:23:37 -08004047 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4048 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004049 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004050 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 return false;
4052 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004053 if (DEBUG_FOCUS) {
4054 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4055 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004058 if (DEBUG_FOCUS) {
4059 ALOGD("Cannot transfer focus because windows are on different displays.");
4060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 return false;
4062 }
4063
4064 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004065 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4066 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004067 for (size_t i = 0; i < state.windows.size(); i++) {
4068 const TouchedWindow& touchedWindow = state.windows[i];
4069 if (touchedWindow.windowHandle == fromWindowHandle) {
4070 int32_t oldTargetFlags = touchedWindow.targetFlags;
4071 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004073 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 int32_t newTargetFlags = oldTargetFlags &
4076 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4077 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004078 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
Jeff Brownf086ddb2014-02-11 14:28:48 -08004080 found = true;
4081 goto Found;
4082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 }
4084 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004088 if (DEBUG_FOCUS) {
4089 ALOGD("Focus transfer failed because from window did not have focus.");
4090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 return false;
4092 }
4093
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004094 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4095 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004096 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 CancelationOptions
4099 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4100 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004102 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 }
4104
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004105 if (DEBUG_FOCUS) {
4106 logDispatchStateLocked();
4107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 } // release lock
4109
4110 // Wake up poll loop since it may need to make new input dispatching choices.
4111 mLooper->wake();
4112 return true;
4113}
4114
4115void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004116 if (DEBUG_FOCUS) {
4117 ALOGD("Resetting and dropping all events (%s).", reason);
4118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
4120 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4121 synthesizeCancelationEventsForAllConnectionsLocked(options);
4122
4123 resetKeyRepeatLocked();
4124 releasePendingEventLocked();
4125 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004126 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004128 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004129 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004131 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132}
4133
4134void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 dumpDispatchStateLocked(dump);
4137
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004138 std::istringstream stream(dump);
4139 std::string line;
4140
4141 while (std::getline(stream, line, '\n')) {
4142 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 }
4144}
4145
Vishnu Nairad321cd2020-08-20 16:40:21 -07004146std::string InputDispatcher::dumpFocusedWindowsLocked() {
4147 if (mFocusedWindowTokenByDisplay.empty()) {
4148 return INDENT "FocusedWindows: <none>\n";
4149 }
4150
4151 std::string dump;
4152 dump += INDENT "FocusedWindows:\n";
4153 for (auto& it : mFocusedWindowTokenByDisplay) {
4154 const int32_t displayId = it.first;
4155 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4156 if (windowHandle) {
4157 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4158 windowHandle->getName().c_str());
4159 } else {
4160 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4161 " has focused token without a window'\n",
4162 displayId);
4163 }
4164 }
4165 return dump;
4166}
4167
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004169 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4170 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4171 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004172 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Tiger Huang721e26f2018-07-24 22:26:19 +08004174 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4175 dump += StringPrintf(INDENT "FocusedApplications:\n");
4176 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4177 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004178 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004179 const std::chrono::duration timeout =
4180 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004182 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004183 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004186 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004188
Vishnu Nairad321cd2020-08-20 16:40:21 -07004189 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004191 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004193 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4194 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 state.displayId, toString(state.down), toString(state.split),
4197 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004198 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004200 for (size_t i = 0; i < state.windows.size(); i++) {
4201 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 dump += StringPrintf(INDENT4
4203 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4204 i, touchedWindow.windowHandle->getName().c_str(),
4205 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004206 }
4207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004209 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004210 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004211 dump += INDENT3 "Portal windows:\n";
4212 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004213 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4215 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004216 }
4217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 }
4219 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 }
4222
Arthur Hungb92218b2018-08-14 12:00:21 +08004223 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004225 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004226 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004227 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004228 dump += INDENT2 "Windows:\n";
4229 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004230 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004231 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232
Arthur Hungb92218b2018-08-14 12:00:21 +08004233 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004234 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4235 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004236 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004238 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 i, windowInfo->name.c_str(), windowInfo->displayId,
4240 windowInfo->portalToDisplayId,
4241 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004242 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 toString(windowInfo->hasWallpaper),
4244 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004245 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004246 static_cast<int32_t>(windowInfo->type),
4247 windowInfo->frameLeft, windowInfo->frameTop,
4248 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004249 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004250 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004251 dump += StringPrintf(", inputFeatures=%s",
4252 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004253 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4254 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004256 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004257 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004258 }
4259 } else {
4260 dump += INDENT2 "Windows: <none>\n";
4261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004264 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
4266
Michael Wright3dd60e22019-03-27 22:06:44 +00004267 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004269 const std::vector<Monitor>& monitors = it.second;
4270 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4271 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 }
4273 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004274 const std::vector<Monitor>& monitors = it.second;
4275 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4276 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004279 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281
4282 nsecs_t currentTime = now();
4283
4284 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004285 if (!mRecentQueue.empty()) {
4286 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4287 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004290 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004293 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295
4296 // Dump event currently being dispatched.
4297 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004298 dump += INDENT "PendingEvent:\n";
4299 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004301 dump += StringPrintf(", age=%" PRId64 "ms\n",
4302 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004304 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306
4307 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004308 if (!mInboundQueue.empty()) {
4309 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4310 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004311 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004313 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004316 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
4318
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004319 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004320 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004321 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4322 const KeyReplacement& replacement = pair.first;
4323 int32_t newKeyCode = pair.second;
4324 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004325 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004326 }
4327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004328 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004329 }
4330
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004331 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004333 for (const auto& pair : mConnectionsByFd) {
4334 const sp<Connection>& connection = pair.second;
4335 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004336 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004337 pair.first, connection->getInputChannelName().c_str(),
4338 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004339 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004341 if (!connection->outboundQueue.empty()) {
4342 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4343 connection->outboundQueue.size());
4344 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 dump.append(INDENT4);
4346 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004347 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4348 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004349 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004350 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
4352 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004353 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 }
4355
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004356 if (!connection->waitQueue.empty()) {
4357 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4358 connection->waitQueue.size());
4359 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004360 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004362 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004363 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004365 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004366 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 }
4368 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 }
4371 }
4372 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004373 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 }
4375
4376 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004377 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4378 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004380 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 }
4382
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004383 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4385 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4386 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387}
4388
Michael Wright3dd60e22019-03-27 22:06:44 +00004389void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4390 const size_t numMonitors = monitors.size();
4391 for (size_t i = 0; i < numMonitors; i++) {
4392 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004393 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004394 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4395 dump += "\n";
4396 }
4397}
4398
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004399status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004401 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402#endif
4403
4404 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004405 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004406 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004407 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 return BAD_VALUE;
4411 }
4412
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004413 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
4415 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004416 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004417 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4420 } // release lock
4421
4422 // Wake the looper because some connections have changed.
4423 mLooper->wake();
4424 return OK;
4425}
4426
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004427status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004428 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004429 { // acquire lock
4430 std::scoped_lock _l(mLock);
4431
4432 if (displayId < 0) {
4433 ALOGW("Attempted to register input monitor without a specified display.");
4434 return BAD_VALUE;
4435 }
4436
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004437 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004438 ALOGW("Attempted to register input monitor without an identifying token.");
4439 return BAD_VALUE;
4440 }
4441
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004442 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004443
4444 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004445 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004446 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 auto& monitorsByDisplay =
4449 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004450 monitorsByDisplay[displayId].emplace_back(inputChannel);
4451
4452 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004453 }
4454 // Wake the looper because some connections have changed.
4455 mLooper->wake();
4456 return OK;
4457}
4458
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004459status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004461 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462#endif
4463
4464 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004465 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
4467 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4468 if (status) {
4469 return status;
4470 }
4471 } // release lock
4472
4473 // Wake the poll loop because removing the connection may have changed the current
4474 // synchronization state.
4475 mLooper->wake();
4476 return OK;
4477}
4478
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004479status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004481 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004482 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004484 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 return BAD_VALUE;
4486 }
4487
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004489 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004490
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 if (connection->monitor) {
4492 removeMonitorChannelLocked(inputChannel);
4493 }
4494
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004495 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
4497 nsecs_t currentTime = now();
4498 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4499
4500 connection->status = Connection::STATUS_ZOMBIE;
4501 return OK;
4502}
4503
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004504void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004505 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4506 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4507}
4508
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004509void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004510 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004511 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004512 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004513 std::vector<Monitor>& monitors = it->second;
4514 const size_t numMonitors = monitors.size();
4515 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004516 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004517 monitors.erase(monitors.begin() + i);
4518 break;
4519 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004520 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004521 if (monitors.empty()) {
4522 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004523 } else {
4524 ++it;
4525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 }
4527}
4528
Michael Wright3dd60e22019-03-27 22:06:44 +00004529status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4530 { // acquire lock
4531 std::scoped_lock _l(mLock);
4532 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4533
4534 if (!foundDisplayId) {
4535 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4536 return BAD_VALUE;
4537 }
4538 int32_t displayId = foundDisplayId.value();
4539
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004540 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4541 mTouchStatesByDisplay.find(displayId);
4542 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004543 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4544 return BAD_VALUE;
4545 }
4546
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004547 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004548 std::optional<int32_t> foundDeviceId;
4549 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004550 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004551 foundDeviceId = state.deviceId;
4552 }
4553 }
4554 if (!foundDeviceId || !state.down) {
4555 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004557 return BAD_VALUE;
4558 }
4559 int32_t deviceId = foundDeviceId.value();
4560
4561 // Send cancel events to all the input channels we're stealing from.
4562 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004564 options.deviceId = deviceId;
4565 options.displayId = displayId;
4566 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004567 std::shared_ptr<InputChannel> channel =
4568 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004569 if (channel != nullptr) {
4570 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4571 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004572 }
4573 // Then clear the current touch state so we stop dispatching to them as well.
4574 state.filterNonMonitors();
4575 }
4576 return OK;
4577}
4578
Michael Wright3dd60e22019-03-27 22:06:44 +00004579std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4580 const sp<IBinder>& token) {
4581 for (const auto& it : mGestureMonitorsByDisplay) {
4582 const std::vector<Monitor>& monitors = it.second;
4583 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004584 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004585 return it.first;
4586 }
4587 }
4588 }
4589 return std::nullopt;
4590}
4591
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004592sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004593 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004594 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004595 }
4596
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004597 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004598 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004599 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004600 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 }
4602 }
Robert Carr4e670e52018-08-15 13:26:12 -07004603
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004604 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605}
4606
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004607void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609 removeByValue(mConnectionsByFd, connection);
4610}
4611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4613 const sp<Connection>& connection, uint32_t seq,
4614 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004615 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4616 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 commandEntry->connection = connection;
4618 commandEntry->eventTime = currentTime;
4619 commandEntry->seq = seq;
4620 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004621 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622}
4623
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004624void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4625 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004627 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004629 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4630 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004632 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633}
4634
Vishnu Nairad321cd2020-08-20 16:40:21 -07004635void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4636 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004637 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4638 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004639 commandEntry->oldToken = oldToken;
4640 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004641 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004642}
4643
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4645 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4646 // is already healthy again. Don't raise ANR in this situation
4647 if (connection->waitQueue.empty()) {
4648 ALOGI("Not raising ANR because the connection %s has recovered",
4649 connection->inputChannel->getName().c_str());
4650 return;
4651 }
4652 /**
4653 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4654 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4655 * has changed. This could cause newer entries to time out before the already dispatched
4656 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4657 * processes the events linearly. So providing information about the oldest entry seems to be
4658 * most useful.
4659 */
4660 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4661 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4662 std::string reason =
4663 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4664 connection->inputChannel->getName().c_str(),
4665 ns2ms(currentWait),
4666 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4669 reason);
4670
4671 std::unique_ptr<CommandEntry> commandEntry =
4672 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4673 commandEntry->inputApplicationHandle = nullptr;
4674 commandEntry->inputChannel = connection->inputChannel;
4675 commandEntry->reason = std::move(reason);
4676 postCommandLocked(std::move(commandEntry));
4677}
4678
Chris Yea209fde2020-07-22 13:54:51 -07004679void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004680 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4681 application->getName().c_str());
4682
4683 updateLastAnrStateLocked(application, reason);
4684
4685 std::unique_ptr<CommandEntry> commandEntry =
4686 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4687 commandEntry->inputApplicationHandle = application;
4688 commandEntry->inputChannel = nullptr;
4689 commandEntry->reason = std::move(reason);
4690 postCommandLocked(std::move(commandEntry));
4691}
4692
4693void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4694 const std::string& reason) {
4695 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4696 updateLastAnrStateLocked(windowLabel, reason);
4697}
4698
Chris Yea209fde2020-07-22 13:54:51 -07004699void InputDispatcher::updateLastAnrStateLocked(
4700 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004701 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4702 updateLastAnrStateLocked(windowLabel, reason);
4703}
4704
4705void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4706 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004708 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 struct tm tm;
4710 localtime_r(&t, &tm);
4711 char timestr[64];
4712 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004713 mLastAnrState.clear();
4714 mLastAnrState += INDENT "ANR:\n";
4715 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004716 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4717 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004718 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719}
4720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 mLock.unlock();
4723
4724 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4725
4726 mLock.lock();
4727}
4728
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 sp<Connection> connection = commandEntry->connection;
4731
4732 if (connection->status != Connection::STATUS_ZOMBIE) {
4733 mLock.unlock();
4734
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004735 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737 mLock.lock();
4738 }
4739}
4740
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004742 sp<IBinder> oldToken = commandEntry->oldToken;
4743 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004744 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004745 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004746 mLock.lock();
4747}
4748
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004749void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004750 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004751 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 mLock.unlock();
4753
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004754 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004755 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
4757 mLock.lock();
4758
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004759 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4761 } else {
4762 // stop waking up for events in this connection, it is already not responding
4763 sp<Connection> connection = getConnectionLocked(token);
4764 if (connection == nullptr) {
4765 return;
4766 }
4767 cancelEventsForAnrLocked(connection);
4768 }
4769}
4770
Chris Yea209fde2020-07-22 13:54:51 -07004771void InputDispatcher::extendAnrTimeoutsLocked(
4772 const std::shared_ptr<InputApplicationHandle>& application,
4773 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 sp<Connection> connection = getConnectionLocked(connectionToken);
4775 if (connection == nullptr) {
4776 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4777 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004778 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004779 mAwaitedFocusedApplication = application;
4780 } else {
4781 // It's also possible that the connection already disappeared. No action necessary.
4782 }
4783 return;
4784 }
4785
4786 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004787 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788
4789 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004790 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 for (DispatchEntry* entry : connection->waitQueue) {
4792 if (newTimeout >= entry->timeoutTime) {
4793 // Already removed old entries when connection was marked unresponsive
4794 entry->timeoutTime = newTimeout;
4795 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4796 }
4797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798}
4799
4800void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4801 CommandEntry* commandEntry) {
4802 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004803 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804
4805 mLock.unlock();
4806
Michael Wright2b3c3302018-03-02 17:19:13 +00004807 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004809 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810 : nullptr;
4811 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004812 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4813 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
4817 mLock.lock();
4818
4819 if (delay < 0) {
4820 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4821 } else if (!delay) {
4822 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4823 } else {
4824 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4825 entry->interceptKeyWakeupTime = now() + delay;
4826 }
4827 entry->release();
4828}
4829
chaviwfd6d3512019-03-25 13:23:49 -07004830void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4831 mLock.unlock();
4832 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4833 mLock.lock();
4834}
4835
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836/**
4837 * Connection is responsive if it has no events in the waitQueue that are older than the
4838 * current time.
4839 */
4840static bool isConnectionResponsive(const Connection& connection) {
4841 const nsecs_t currentTime = now();
4842 for (const DispatchEntry* entry : connection.waitQueue) {
4843 if (entry->timeoutTime < currentTime) {
4844 return false;
4845 }
4846 }
4847 return true;
4848}
4849
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004850void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004852 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004854 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
4856 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004857 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004858 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004859 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004861 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004862 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004863 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004864 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4865 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004866 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004867 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868
4869 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004870 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004871 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4872 restartEvent =
4873 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004874 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004875 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4876 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4877 handled);
4878 } else {
4879 restartEvent = false;
4880 }
4881
4882 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004883 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004884 // contents of the wait queue to have been drained, so we need to double-check
4885 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004886 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4887 if (dispatchEntryIt != connection->waitQueue.end()) {
4888 dispatchEntry = *dispatchEntryIt;
4889 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890 mAnrTracker.erase(dispatchEntry->timeoutTime,
4891 connection->inputChannel->getConnectionToken());
4892 if (!connection->responsive) {
4893 connection->responsive = isConnectionResponsive(*connection);
4894 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004895 traceWaitQueueLength(connection);
4896 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004897 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004898 traceOutboundQueueLength(connection);
4899 } else {
4900 releaseDispatchEntry(dispatchEntry);
4901 }
4902 }
4903
4904 // Start the next dispatch cycle for this connection.
4905 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906}
4907
4908bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004909 DispatchEntry* dispatchEntry,
4910 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004911 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004912 if (!handled) {
4913 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004914 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004915 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916 return false;
4917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004919 // Get the fallback key state.
4920 // Clear it out after dispatching the UP.
4921 int32_t originalKeyCode = keyEntry->keyCode;
4922 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4923 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4924 connection->inputState.removeFallbackKey(originalKeyCode);
4925 }
4926
4927 if (handled || !dispatchEntry->hasForegroundTarget()) {
4928 // If the application handles the original key for which we previously
4929 // generated a fallback or if the window is not a foreground window,
4930 // then cancel the associated fallback key, if any.
4931 if (fallbackKeyCode != -1) {
4932 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004935 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4936 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4937 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004939 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004940 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
4942 mLock.unlock();
4943
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004944 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946
4947 mLock.lock();
4948
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004949 // Cancel the fallback key.
4950 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 "application handled the original non-fallback key "
4953 "or is no longer a foreground target, "
4954 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 options.keyCode = fallbackKeyCode;
4956 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004958 connection->inputState.removeFallbackKey(originalKeyCode);
4959 }
4960 } else {
4961 // If the application did not handle a non-fallback key, first check
4962 // that we are in a good state to perform unhandled key event processing
4963 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004964 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004965 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004967 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004968 "since this is not an initial down. "
4969 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4970 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004972 return false;
4973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975 // Dispatch the unhandled key to the policy.
4976#if DEBUG_OUTBOUND_EVENT_DETAILS
4977 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4979 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004980#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004981 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982
4983 mLock.unlock();
4984
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004985 bool fallback =
4986 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4987 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004988
4989 mLock.lock();
4990
4991 if (connection->status != Connection::STATUS_NORMAL) {
4992 connection->inputState.removeFallbackKey(originalKeyCode);
4993 return false;
4994 }
4995
4996 // Latch the fallback keycode for this key on an initial down.
4997 // The fallback keycode cannot change at any other point in the lifecycle.
4998 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005000 fallbackKeyCode = event.getKeyCode();
5001 } else {
5002 fallbackKeyCode = AKEYCODE_UNKNOWN;
5003 }
5004 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5005 }
5006
5007 ALOG_ASSERT(fallbackKeyCode != -1);
5008
5009 // Cancel the fallback key if the policy decides not to send it anymore.
5010 // We will continue to dispatch the key to the policy but we will no
5011 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005012 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5013 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005014#if DEBUG_OUTBOUND_EVENT_DETAILS
5015 if (fallback) {
5016 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005017 "as a fallback for %d, but on the DOWN it had requested "
5018 "to send %d instead. Fallback canceled.",
5019 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005020 } else {
5021 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 "but on the DOWN it had requested to send %d. "
5023 "Fallback canceled.",
5024 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005025 }
5026#endif
5027
5028 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5029 "canceling fallback, policy no longer desires it");
5030 options.keyCode = fallbackKeyCode;
5031 synthesizeCancelationEventsForConnectionLocked(connection, options);
5032
5033 fallback = false;
5034 fallbackKeyCode = AKEYCODE_UNKNOWN;
5035 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005037 }
5038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039
5040#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005041 {
5042 std::string msg;
5043 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5044 connection->inputState.getFallbackKeys();
5045 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005046 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005048 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005049 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005050 }
5051#endif
5052
5053 if (fallback) {
5054 // Restart the dispatch cycle using the fallback key.
5055 keyEntry->eventTime = event.getEventTime();
5056 keyEntry->deviceId = event.getDeviceId();
5057 keyEntry->source = event.getSource();
5058 keyEntry->displayId = event.getDisplayId();
5059 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5060 keyEntry->keyCode = fallbackKeyCode;
5061 keyEntry->scanCode = event.getScanCode();
5062 keyEntry->metaState = event.getMetaState();
5063 keyEntry->repeatCount = event.getRepeatCount();
5064 keyEntry->downTime = event.getDownTime();
5065 keyEntry->syntheticRepeat = false;
5066
5067#if DEBUG_OUTBOUND_EVENT_DETAILS
5068 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005069 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5070 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005071#endif
5072 return true; // restart the event
5073 } else {
5074#if DEBUG_OUTBOUND_EVENT_DETAILS
5075 ALOGD("Unhandled key event: No fallback key.");
5076#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005077
5078 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005079 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081 }
5082 return false;
5083}
5084
5085bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005086 DispatchEntry* dispatchEntry,
5087 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088 return false;
5089}
5090
5091void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5092 mLock.unlock();
5093
5094 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5095
5096 mLock.lock();
5097}
5098
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005099KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5100 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005101 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005102 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5103 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005104 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105}
5106
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005107void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5108 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 // TODO Write some statistics about how long we spend waiting.
5110}
5111
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005112/**
5113 * Report the touch event latency to the statsd server.
5114 * Input events are reported for statistics if:
5115 * - This is a touchscreen event
5116 * - InputFilter is not enabled
5117 * - Event is not injected or synthesized
5118 *
5119 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5120 * from getting aggregated with the "old" data.
5121 */
5122void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5123 REQUIRES(mLock) {
5124 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5125 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5126 if (!reportForStatistics) {
5127 return;
5128 }
5129
5130 if (mTouchStatistics.shouldReport()) {
5131 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5132 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5133 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5134 mTouchStatistics.reset();
5135 }
5136 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5137 mTouchStatistics.addValue(latencyMicros);
5138}
5139
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140void InputDispatcher::traceInboundQueueLengthLocked() {
5141 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005142 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144}
5145
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005146void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 if (ATRACE_ENABLED()) {
5148 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005149 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005150 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 }
5152}
5153
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005154void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 if (ATRACE_ENABLED()) {
5156 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005157 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005158 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160}
5161
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005162void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005163 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 dumpDispatchStateLocked(dump);
5167
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005168 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005170 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
5172}
5173
5174void InputDispatcher::monitor() {
5175 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005176 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005178 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179}
5180
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005181/**
5182 * Wake up the dispatcher and wait until it processes all events and commands.
5183 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5184 * this method can be safely called from any thread, as long as you've ensured that
5185 * the work you are interested in completing has already been queued.
5186 */
5187bool InputDispatcher::waitForIdle() {
5188 /**
5189 * Timeout should represent the longest possible time that a device might spend processing
5190 * events and commands.
5191 */
5192 constexpr std::chrono::duration TIMEOUT = 100ms;
5193 std::unique_lock lock(mLock);
5194 mLooper->wake();
5195 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5196 return result == std::cv_status::no_timeout;
5197}
5198
Vishnu Naire798b472020-07-23 13:52:21 -07005199/**
5200 * Sets focus to the window identified by the token. This must be called
5201 * after updating any input window handles.
5202 *
5203 * Params:
5204 * request.token - input channel token used to identify the window that should gain focus.
5205 * request.focusedToken - the token that the caller expects currently to be focused. If the
5206 * specified token does not match the currently focused window, this request will be dropped.
5207 * If the specified focused token matches the currently focused window, the call will succeed.
5208 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5209 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5210 * when requesting the focus change. This determines which request gets
5211 * precedence if there is a focus change request from another source such as pointer down.
5212 */
Vishnu Nair958da932020-08-21 17:12:37 -07005213void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5214 { // acquire lock
5215 std::scoped_lock _l(mLock);
5216
5217 const int32_t displayId = request.displayId;
5218 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5219 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5220 ALOGD_IF(DEBUG_FOCUS,
5221 "setFocusedWindow on display %" PRId32
5222 " ignored, reason: focusedToken is not focused",
5223 displayId);
5224 return;
5225 }
5226
5227 mPendingFocusRequests.erase(displayId);
5228 FocusResult result = handleFocusRequestLocked(request);
5229 if (result == FocusResult::NOT_VISIBLE) {
5230 // The requested window is not currently visible. Wait for the window to become visible
5231 // and then provide it focus. This is to handle situations where a user action triggers
5232 // a new window to appear. We want to be able to queue any key events after the user
5233 // action and deliver it to the newly focused window. In order for this to happen, we
5234 // take focus from the currently focused window so key events can be queued.
5235 ALOGD_IF(DEBUG_FOCUS,
5236 "setFocusedWindow on display %" PRId32
5237 " pending, reason: window is not visible",
5238 displayId);
5239 mPendingFocusRequests[displayId] = request;
5240 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5241 "setFocusedWindow_AwaitingWindowVisibility");
5242 } else if (result != FocusResult::OK) {
5243 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5244 typeToString(result));
5245 }
5246 } // release lock
5247 // Wake up poll loop since it may need to make new input dispatching choices.
5248 mLooper->wake();
5249}
5250
5251InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5252 const FocusRequest& request) {
5253 const int32_t displayId = request.displayId;
5254 const sp<IBinder> newFocusedToken = request.token;
5255 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5256
5257 if (oldFocusedToken == request.token) {
5258 ALOGD_IF(DEBUG_FOCUS,
5259 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5260 displayId);
5261 return FocusResult::OK;
5262 }
5263
5264 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5265 if (result != FocusResult::OK) {
5266 return result;
5267 }
5268
5269 std::string_view reason =
5270 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5271 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5272 return FocusResult::OK;
5273}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005274
Vishnu Nairad321cd2020-08-20 16:40:21 -07005275void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5276 const sp<IBinder>& newFocusedToken, int32_t displayId,
5277 std::string_view reason) {
5278 if (oldFocusedToken) {
5279 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005280 if (focusedInputChannel) {
5281 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5282 "focus left window");
5283 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005284 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005285 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005286 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005287 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005288 if (newFocusedToken) {
5289 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5290 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005291 }
5292
5293 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005294 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005295 }
5296}
Vishnu Nair958da932020-08-21 17:12:37 -07005297
5298/**
5299 * Checks if the window token can be focused on a display. The token can be focused if there is
5300 * at least one window handle that is visible with the same token and all window handles with the
5301 * same token are focusable.
5302 *
5303 * In the case of mirroring, two windows may share the same window token and their visibility
5304 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5305 * we expect the focusability of the windows to match since its hard to reason why one window can
5306 * receive focus events and the other cannot when both are backed by the same input channel.
5307 */
5308InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5309 int32_t displayId) const {
5310 bool allWindowsAreFocusable = true;
5311 bool visibleWindowFound = false;
5312 bool windowFound = false;
5313 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5314 if (window->getToken() != token) {
5315 continue;
5316 }
5317 windowFound = true;
5318 if (window->getInfo()->visible) {
5319 // Check if at least a single window is visible.
5320 visibleWindowFound = true;
5321 }
5322 if (!window->getInfo()->focusable) {
5323 // Check if all windows with the window token are focusable.
5324 allWindowsAreFocusable = false;
5325 break;
5326 }
5327 }
5328
5329 if (!windowFound) {
5330 return FocusResult::NO_WINDOW;
5331 }
5332 if (!allWindowsAreFocusable) {
5333 return FocusResult::NOT_FOCUSABLE;
5334 }
5335 if (!visibleWindowFound) {
5336 return FocusResult::NOT_VISIBLE;
5337 }
5338
5339 return FocusResult::OK;
5340}
Garfield Tane84e6f92019-08-29 17:28:41 -07005341} // namespace android::inputdispatcher