blob: a9aebdfedd85587f1b36f4820df1d97173670d30 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080077using android::os::BlockUntrustedTouchesMode;
78using android::os::InputEventInjectionResult;
79using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080080
Garfield Tane84e6f92019-08-29 17:28:41 -070081namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Default input dispatching timeout if there is no focused application or paused window
84// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050085constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
86 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for all pending events to be processed when an app switch
89// key is on the way. This is used to preempt input dispatch and drop input events
90// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Amount of time to allow for an event to be dispatched (measured since its eventTime)
94// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// 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 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111// Event log tags. See EventLogTags.logtags for reference
112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115static inline nsecs_t now() {
116 return systemTime(SYSTEM_TIME_MONOTONIC);
117}
118
119static inline const char* toString(bool value) {
120 return value ? "true" : "false";
121}
122
123static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700124 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
125 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126}
127
128static bool isValidKeyAction(int32_t action) {
129 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 case AKEY_EVENT_ACTION_DOWN:
131 case AKEY_EVENT_ACTION_UP:
132 return true;
133 default:
134 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 }
136}
137
138static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 ALOGE("Key event has invalid action code 0x%x", action);
141 return false;
142 }
143 return true;
144}
145
Michael Wright7b159c92015-05-14 14:48:03 +0100146static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 case AMOTION_EVENT_ACTION_DOWN:
149 case AMOTION_EVENT_ACTION_UP:
150 case AMOTION_EVENT_ACTION_CANCEL:
151 case AMOTION_EVENT_ACTION_MOVE:
152 case AMOTION_EVENT_ACTION_OUTSIDE:
153 case AMOTION_EVENT_ACTION_HOVER_ENTER:
154 case AMOTION_EVENT_ACTION_HOVER_MOVE:
155 case AMOTION_EVENT_ACTION_HOVER_EXIT:
156 case AMOTION_EVENT_ACTION_SCROLL:
157 return true;
158 case AMOTION_EVENT_ACTION_POINTER_DOWN:
159 case AMOTION_EVENT_ACTION_POINTER_UP: {
160 int32_t index = getMotionEventActionPointerIndex(action);
161 return index >= 0 && index < pointerCount;
162 }
163 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
164 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
165 return actionButton != 0;
166 default:
167 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 }
169}
170
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500171static int64_t millis(std::chrono::nanoseconds t) {
172 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
173}
174
Michael Wright7b159c92015-05-14 14:48:03 +0100175static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 const PointerProperties* pointerProperties) {
177 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 ALOGE("Motion event has invalid action code 0x%x", action);
179 return false;
180 }
181 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000182 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return false;
185 }
186 BitSet32 pointerIdBits;
187 for (size_t i = 0; i < pointerCount; i++) {
188 int32_t id = pointerProperties[i].id;
189 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
191 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 return false;
193 }
194 if (pointerIdBits.hasBit(id)) {
195 ALOGE("Motion event has duplicate pointer id %d", id);
196 return false;
197 }
198 pointerIdBits.markBit(id);
199 }
200 return true;
201}
202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 return;
207 }
208
209 bool first = true;
210 Region::const_iterator cur = region.begin();
211 Region::const_iterator const tail = region.end();
212 while (cur != tail) {
213 if (first) {
214 first = false;
215 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800216 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 cur++;
220 }
221}
222
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700223/**
224 * Find the entry in std::unordered_map by key, and return it.
225 * If the entry is not found, return a default constructed entry.
226 *
227 * Useful when the entries are vectors, since an empty vector will be returned
228 * if the entry is not found.
229 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
230 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231template <typename K, typename V>
232static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700233 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800235}
236
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700237/**
238 * Find the entry in std::unordered_map by value, and remove it.
239 * If more than one entry has the same value, then all matching
240 * key-value pairs will be removed.
241 *
242 * Return true if at least one value has been removed.
243 */
244template <typename K, typename V>
245static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
246 bool removed = false;
247 for (auto it = map.begin(); it != map.end();) {
248 if (it->second == value) {
249 it = map.erase(it);
250 removed = true;
251 } else {
252 it++;
253 }
254 }
255 return removed;
256}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257
Vishnu Nair958da932020-08-21 17:12:37 -0700258/**
259 * Find the entry in std::unordered_map by key and return the value as an optional.
260 */
261template <typename K, typename V>
262static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
263 auto it = map.find(key);
264 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
265}
266
chaviwaf87b3e2019-10-01 16:59:28 -0700267static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
268 if (first == second) {
269 return true;
270 }
271
272 if (first == nullptr || second == nullptr) {
273 return false;
274 }
275
276 return first->getToken() == second->getToken();
277}
278
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800279static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
280 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
281}
282
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000283static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
284 EventEntry* eventEntry,
285 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700286 if (inputTarget.useDefaultPointerTransform()) {
287 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000288 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700289 inputTargetFlags, transform,
290 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000291 }
292
293 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
294 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
295
296 PointerCoords pointerCoords[motionEntry.pointerCount];
297
298 // Use the first pointer information to normalize all other pointers. This could be any pointer
299 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700300 // uses the transform for the normalized pointer.
301 const ui::Transform& firstPointerTransform =
302 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
303 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000304
305 // Iterate through all pointers in the event to normalize against the first.
306 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
307 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
308 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310
311 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700312 // First, apply the current pointer's transform to update the coordinates into
313 // window space.
314 pointerCoords[pointerIndex].transform(currTransform);
315 // Next, apply the inverse transform of the normalized coordinates so the
316 // current coordinates are transformed into the normalized coordinate space.
317 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318 }
319
320 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800321 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
323 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
324 motionEntry.metaState, motionEntry.buttonState,
325 motionEntry.classification, motionEntry.edgeFlags,
326 motionEntry.xPrecision, motionEntry.yPrecision,
327 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
328 motionEntry.downTime, motionEntry.pointerCount,
329 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
330 0 /* yOffset */);
331
332 if (motionEntry.injectionState) {
333 combinedMotionEntry->injectionState = motionEntry.injectionState;
334 combinedMotionEntry->injectionState->refCount += 1;
335 }
336
337 std::unique_ptr<DispatchEntry> dispatchEntry =
338 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 inputTargetFlags, firstPointerTransform,
340 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000341 combinedMotionEntry->release();
342 return dispatchEntry;
343}
344
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700345static void addGestureMonitors(const std::vector<Monitor>& monitors,
346 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
347 float yOffset = 0) {
348 if (monitors.empty()) {
349 return;
350 }
351 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
352 for (const Monitor& monitor : monitors) {
353 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
354 }
355}
356
Garfield Tan15601662020-09-22 15:32:38 -0700357static status_t openInputChannelPair(const std::string& name,
358 std::shared_ptr<InputChannel>& serverChannel,
359 std::unique_ptr<InputChannel>& clientChannel) {
360 std::unique_ptr<InputChannel> uniqueServerChannel;
361 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
362
363 serverChannel = std::move(uniqueServerChannel);
364 return result;
365}
366
Vishnu Nair958da932020-08-21 17:12:37 -0700367const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
368 switch (result) {
369 case InputDispatcher::FocusResult::OK:
370 return "Ok";
371 case InputDispatcher::FocusResult::NO_WINDOW:
372 return "Window not found";
373 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
374 return "Window not focusable";
375 case InputDispatcher::FocusResult::NOT_VISIBLE:
376 return "Window not visible";
377 }
378}
379
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500380template <typename T>
381static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
382 if (lhs == nullptr && rhs == nullptr) {
383 return true;
384 }
385 if (lhs == nullptr || rhs == nullptr) {
386 return false;
387 }
388 return *lhs == *rhs;
389}
390
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391// --- InputDispatcher ---
392
Garfield Tan00f511d2019-06-12 16:55:40 -0700393InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
394 : mPolicy(policy),
395 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700396 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800397 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700398 mAppSwitchSawKeyDown(false),
399 mAppSwitchDueTime(LONG_LONG_MAX),
400 mNextUnblockedEvent(nullptr),
401 mDispatchEnabled(false),
402 mDispatchFrozen(false),
403 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800404 // mInTouchMode will be initialized by the WindowManager to the default device config.
405 // To avoid leaking stack in case that call never comes, and for tests,
406 // initialize it here anyways.
407 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100408 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700409 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800411 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412
Yi Kong9b14ac62018-07-17 13:48:38 -0700413 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
415 policy->getDispatcherConfiguration(&mConfig);
416}
417
418InputDispatcher::~InputDispatcher() {
419 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800420 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421
422 resetKeyRepeatLocked();
423 releasePendingEventLocked();
424 drainInboundQueueLocked();
425 }
426
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700427 while (!mConnectionsByFd.empty()) {
428 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700429 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 }
431}
432
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700433status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700435 return ALREADY_EXISTS;
436 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700437 mThread = std::make_unique<InputThread>(
438 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
439 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700440}
441
442status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700443 if (mThread && mThread->isCallingThread()) {
444 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700445 return INVALID_OPERATION;
446 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700447 mThread.reset();
448 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700449}
450
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451void InputDispatcher::dispatchOnce() {
452 nsecs_t nextWakeupTime = LONG_LONG_MAX;
453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800454 std::scoped_lock _l(mLock);
455 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
457 // Run a dispatch loop if there are no pending commands.
458 // The dispatch loop might enqueue commands to run afterwards.
459 if (!haveCommandsLocked()) {
460 dispatchOnceInnerLocked(&nextWakeupTime);
461 }
462
463 // Run all pending commands if there are any.
464 // If any commands were run then force the next poll to wake up immediately.
465 if (runCommandsLockedInterruptible()) {
466 nextWakeupTime = LONG_LONG_MIN;
467 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800468
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700469 // If we are still waiting for ack on some events,
470 // we might have to wake up earlier to check if an app is anr'ing.
471 const nsecs_t nextAnrCheck = processAnrsLocked();
472 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
473
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800474 // We are about to enter an infinitely long sleep, because we have no commands or
475 // pending or queued events
476 if (nextWakeupTime == LONG_LONG_MAX) {
477 mDispatcherEnteredIdle.notify_all();
478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 } // release lock
480
481 // Wait for callback or timeout or wake. (make sure we round up, not down)
482 nsecs_t currentTime = now();
483 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
484 mLooper->pollOnce(timeoutMillis);
485}
486
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700487/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500488 * Raise ANR if there is no focused window.
489 * Before the ANR is raised, do a final state check:
490 * 1. The currently focused application must be the same one we are waiting for.
491 * 2. Ensure we still don't have a focused window.
492 */
493void InputDispatcher::processNoFocusedWindowAnrLocked() {
494 // Check if the application that we are waiting for is still focused.
495 std::shared_ptr<InputApplicationHandle> focusedApplication =
496 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
497 if (focusedApplication == nullptr ||
498 focusedApplication->getApplicationToken() !=
499 mAwaitedFocusedApplication->getApplicationToken()) {
500 // Unexpected because we should have reset the ANR timer when focused application changed
501 ALOGE("Waited for a focused window, but focused application has already changed to %s",
502 focusedApplication->getName().c_str());
503 return; // The focused application has changed.
504 }
505
506 const sp<InputWindowHandle>& focusedWindowHandle =
507 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
508 if (focusedWindowHandle != nullptr) {
509 return; // We now have a focused window. No need for ANR.
510 }
511 onAnrLocked(mAwaitedFocusedApplication);
512}
513
514/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700515 * Check if any of the connections' wait queues have events that are too old.
516 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
517 * Return the time at which we should wake up next.
518 */
519nsecs_t InputDispatcher::processAnrsLocked() {
520 const nsecs_t currentTime = now();
521 nsecs_t nextAnrCheck = LONG_LONG_MAX;
522 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
523 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
524 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500525 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700526 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500527 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700528 return LONG_LONG_MIN;
529 } else {
530 // Keep waiting
531 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
532 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
533 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
534 }
535 }
536
537 // Check if any connection ANRs are due
538 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
539 if (currentTime < nextAnrCheck) { // most likely scenario
540 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
541 }
542
543 // If we reached here, we have an unresponsive connection.
544 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
545 if (connection == nullptr) {
546 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
547 return nextAnrCheck;
548 }
549 connection->responsive = false;
550 // Stop waking up for this unresponsive connection
551 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500552 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700553 return LONG_LONG_MIN;
554}
555
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500556std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700557 sp<InputWindowHandle> window = getWindowHandleLocked(token);
558 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500559 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700560 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500561 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700562}
563
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
565 nsecs_t currentTime = now();
566
Jeff Browndc5992e2014-04-11 01:27:26 -0700567 // Reset the key repeat timer whenever normal dispatch is suspended while the
568 // device is in a non-interactive state. This is to ensure that we abort a key
569 // repeat if the device is just coming out of sleep.
570 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571 resetKeyRepeatLocked();
572 }
573
574 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
575 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100576 if (DEBUG_FOCUS) {
577 ALOGD("Dispatch frozen. Waiting some more.");
578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 return;
580 }
581
582 // Optimize latency of app switches.
583 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
584 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
585 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
586 if (mAppSwitchDueTime < *nextWakeupTime) {
587 *nextWakeupTime = mAppSwitchDueTime;
588 }
589
590 // Ready to start a new event.
591 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700592 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700593 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 if (isAppSwitchDue) {
595 // The inbound queue is empty so the app switch key we were waiting
596 // for will never arrive. Stop waiting for it.
597 resetPendingAppSwitchLocked(false);
598 isAppSwitchDue = false;
599 }
600
601 // Synthesize a key repeat if appropriate.
602 if (mKeyRepeatState.lastKeyEntry) {
603 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
604 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
605 } else {
606 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
607 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
608 }
609 }
610 }
611
612 // Nothing to do if there is no pending event.
613 if (!mPendingEvent) {
614 return;
615 }
616 } else {
617 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700618 mPendingEvent = mInboundQueue.front();
619 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 traceInboundQueueLengthLocked();
621 }
622
623 // Poke user activity for this event.
624 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700625 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628
629 // Now we have an event to dispatch.
630 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700631 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700633 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700635 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 }
639
640 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700641 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 }
643
644 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700645 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700646 ConfigurationChangedEntry* typedEntry =
647 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
648 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700649 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 break;
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700653 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
655 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700656 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 break;
658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100660 case EventEntry::Type::FOCUS: {
661 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
662 dispatchFocusLocked(currentTime, typedEntry);
663 done = true;
664 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
665 break;
666 }
667
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700668 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
670 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700671 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700672 resetPendingAppSwitchLocked(true);
673 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 } else if (dropReason == DropReason::NOT_DROPPED) {
675 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 }
677 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700678 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700681 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
682 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 }
684 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
685 break;
686 }
687
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700688 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700689 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700690 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
691 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700693 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700694 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700696 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
697 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700698 }
699 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
700 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
703
704 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700705 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700706 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 }
Michael Wright3a981722015-06-10 15:26:13 +0100708 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709
710 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
713}
714
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700715/**
716 * Return true if the events preceding this incoming motion event should be dropped
717 * Return false otherwise (the default behaviour)
718 */
719bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700720 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700721 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700722
723 // Optimize case where the current application is unresponsive and the user
724 // decides to touch a window in a different application.
725 // If the application takes too long to catch up then we drop all events preceding
726 // the touch into the other window.
727 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700728 int32_t displayId = motionEntry.displayId;
729 int32_t x = static_cast<int32_t>(
730 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
731 int32_t y = static_cast<int32_t>(
732 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
733 sp<InputWindowHandle> touchedWindowHandle =
734 findTouchedWindowAtLocked(displayId, x, y, nullptr);
735 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 touchedWindowHandle->getApplicationToken() !=
737 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700738 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739 ALOGI("Pruning input queue because user touched a different application while waiting "
740 "for %s",
741 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700742 return true;
743 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700744
745 // Alternatively, maybe there's a gesture monitor that could handle this event
746 std::vector<TouchedMonitor> gestureMonitors =
747 findTouchedGestureMonitorsLocked(displayId, {});
748 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
749 sp<Connection> connection =
750 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000751 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700752 // This monitor could take more input. Drop all events preceding this
753 // event, so that gesture monitor could get a chance to receive the stream
754 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
755 "responsive gesture monitor that may handle the event",
756 mAwaitedFocusedApplication->getName().c_str());
757 return true;
758 }
759 }
760 }
761
762 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
763 // yet been processed by some connections, the dispatcher will wait for these motion
764 // events to be processed before dispatching the key event. This is because these motion events
765 // may cause a new window to be launched, which the user might expect to receive focus.
766 // To prevent waiting forever for such events, just send the key to the currently focused window
767 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
768 ALOGD("Received a new pointer down event, stop waiting for events to process and "
769 "just send the pending key event to the focused window.");
770 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700771 }
772 return false;
773}
774
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700776 bool needWake = mInboundQueue.empty();
777 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 traceInboundQueueLengthLocked();
779
780 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700781 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 // Optimize app switch latency.
783 // If the application takes too long to catch up then we drop all events preceding
784 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700785 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700787 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700789 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700790 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700794 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 mAppSwitchSawKeyDown = false;
796 needWake = true;
797 }
798 }
799 }
800 break;
801 }
802
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700803 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700804 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
805 mNextUnblockedEvent = entry;
806 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100810 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700811 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
812 break;
813 }
814 case EventEntry::Type::CONFIGURATION_CHANGED:
815 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700816 // nothing to do
817 break;
818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 }
820
821 return needWake;
822}
823
824void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
825 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700826 mRecentQueue.push_back(entry);
827 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
828 mRecentQueue.front()->release();
829 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 }
831}
832
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 int32_t y, TouchState* touchState,
835 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700837 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
838 LOG_ALWAYS_FATAL(
839 "Must provide a valid touch state if adding portal windows or outside targets");
840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700842 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800843 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 const InputWindowInfo* windowInfo = windowHandle->getInfo();
845 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100846 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847
848 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100849 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
850 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
851 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800853 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 if (portalToDisplayId != ADISPLAY_ID_NONE &&
855 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800856 if (addPortalWindows) {
857 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700858 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800859 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700860 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 // Found window.
864 return windowHandle;
865 }
866 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800867
Michael Wright44753b12020-07-08 13:48:11 +0100868 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700869 touchState->addOrUpdateWindow(windowHandle,
870 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
871 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700876 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
Garfield Tane84e6f92019-08-29 17:28:41 -0700879std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700880 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000881 std::vector<TouchedMonitor> touchedMonitors;
882
883 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
884 addGestureMonitors(monitors, touchedMonitors);
885 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
886 const InputWindowInfo* windowInfo = portalWindow->getInfo();
887 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
889 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000890 }
891 return touchedMonitors;
892}
893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 const char* reason;
896 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 reason = "inbound event was dropped because the policy consumed it";
902 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 case DropReason::DISABLED:
904 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 ALOGI("Dropped event because input dispatch is disabled.");
906 }
907 reason = "inbound event was dropped because input dispatch is disabled";
908 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700909 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 ALOGI("Dropped event because of pending overdue app switch.");
911 reason = "inbound event was dropped because of pending overdue app switch";
912 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700913 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 ALOGI("Dropped event because the current application is not responding and the user "
915 "has started interacting with a different application.");
916 reason = "inbound event was dropped because the current application is not responding "
917 "and the user has started interacting with a different application";
918 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700919 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 ALOGI("Dropped event because it is stale.");
921 reason = "inbound event was dropped because it is stale";
922 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 case DropReason::NOT_DROPPED: {
924 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700930 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
932 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700935 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700936 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
937 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
939 synthesizeCancelationEventsForAllConnectionsLocked(options);
940 } else {
941 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
942 synthesizeCancelationEventsForAllConnectionsLocked(options);
943 }
944 break;
945 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100946 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700947 case EventEntry::Type::CONFIGURATION_CHANGED:
948 case EventEntry::Type::DEVICE_RESET: {
949 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
950 break;
951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
953}
954
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800955static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
957 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700960bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
961 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
962 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
963 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964}
965
966bool InputDispatcher::isAppSwitchPendingLocked() {
967 return mAppSwitchDueTime != LONG_LONG_MAX;
968}
969
970void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
971 mAppSwitchDueTime = LONG_LONG_MAX;
972
973#if DEBUG_APP_SWITCH
974 if (handled) {
975 ALOGD("App switch has arrived.");
976 } else {
977 ALOGD("App switch was abandoned.");
978 }
979#endif
980}
981
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700983 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984}
985
986bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700987 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 return false;
989 }
990
991 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700992 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700993 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700995 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996
997 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700998 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 return true;
1000}
1001
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001002void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1003 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004}
1005
1006void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001007 while (!mInboundQueue.empty()) {
1008 EventEntry* entry = mInboundQueue.front();
1009 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 releaseInboundEventLocked(entry);
1011 }
1012 traceInboundQueueLengthLocked();
1013}
1014
1015void InputDispatcher::releasePendingEventLocked() {
1016 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001018 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 }
1020}
1021
1022void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1023 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001024 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025#if DEBUG_DISPATCH_CYCLE
1026 ALOGD("Injected inbound event was dropped.");
1027#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001028 setInjectionResult(entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001031 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
1033 addRecentEventLocked(entry);
1034 entry->release();
1035}
1036
1037void InputDispatcher::resetKeyRepeatLocked() {
1038 if (mKeyRepeatState.lastKeyEntry) {
1039 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042}
1043
Garfield Tane84e6f92019-08-29 17:28:41 -07001044KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1046
1047 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001048 uint32_t policyFlags = entry->policyFlags &
1049 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 if (entry->refCount == 1) {
1051 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001052 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 entry->eventTime = currentTime;
1054 entry->policyFlags = policyFlags;
1055 entry->repeatCount += 1;
1056 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001058 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001059 entry->displayId, policyFlags, entry->action, entry->flags,
1060 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062
1063 mKeyRepeatState.lastKeyEntry = newEntry;
1064 entry->release();
1065
1066 entry = newEntry;
1067 }
1068 entry->syntheticRepeat = true;
1069
1070 // Increment reference count since we keep a reference to the event in
1071 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1072 entry->refCount += 1;
1073
1074 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1075 return entry;
1076}
1077
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1079 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001081 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082#endif
1083
1084 // Reset key repeating in case a keyboard device was added or removed or something.
1085 resetKeyRepeatLocked();
1086
1087 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1089 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001091 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 return true;
1093}
1094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001097 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099#endif
1100
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 options.deviceId = entry->deviceId;
1103 synthesizeCancelationEventsForAllConnectionsLocked(options);
1104 return true;
1105}
1106
Vishnu Nairad321cd2020-08-20 16:40:21 -07001107void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001108 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001109 if (mPendingEvent != nullptr) {
1110 // Move the pending event to the front of the queue. This will give the chance
1111 // for the pending event to get dispatched to the newly focused window
1112 mInboundQueue.push_front(mPendingEvent);
1113 mPendingEvent = nullptr;
1114 }
1115
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001116 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001117 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118
1119 // This event should go to the front of the queue, but behind all other focus events
1120 // Find the last focus event, and insert right after it
1121 std::deque<EventEntry*>::reverse_iterator it =
1122 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1123 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1124
1125 // Maintain the order of focus events. Insert the entry after all other focus events.
1126 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001127}
1128
1129void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001130 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001131 if (channel == nullptr) {
1132 return; // Window has gone away
1133 }
1134 InputTarget target;
1135 target.inputChannel = channel;
1136 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1137 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001138 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1139 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001140 std::string reason = std::string("reason=").append(entry->reason);
1141 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 dispatchEventLocked(currentTime, entry, {target});
1143}
1144
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 if (!entry->dispatchInProgress) {
1149 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1150 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1151 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1152 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001153 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 // We have seen two identical key downs in a row which indicates that the device
1155 // driver is automatically generating key repeats itself. We take note of the
1156 // repeat here, but we disable our own next key repeat timer since it is clear that
1157 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001158 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1159 // Make sure we don't get key down from a different device. If a different
1160 // device Id has same key pressed down, the new device Id will replace the
1161 // current one to hold the key repeat with repeat count reset.
1162 // In the future when got a KEY_UP on the device id, drop it and do not
1163 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1165 resetKeyRepeatLocked();
1166 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1167 } else {
1168 // Not a repeat. Save key down state in case we do see a repeat later.
1169 resetKeyRepeatLocked();
1170 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1171 }
1172 mKeyRepeatState.lastKeyEntry = entry;
1173 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001174 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1175 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1176 // The stale device releases the key, reset staleDeviceId.
1177#if DEBUG_INBOUND_EVENT_DETAILS
1178 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1179#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 resetKeyRepeatLocked();
1182 }
1183
1184 if (entry->repeatCount == 1) {
1185 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1186 } else {
1187 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1188 }
1189
1190 entry->dispatchInProgress = true;
1191
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001192 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
1194
1195 // Handle case where the policy asked us to try again later last time.
1196 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1197 if (currentTime < entry->interceptKeyWakeupTime) {
1198 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1199 *nextWakeupTime = entry->interceptKeyWakeupTime;
1200 }
1201 return false; // wait until next wakeup
1202 }
1203 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1204 entry->interceptKeyWakeupTime = 0;
1205 }
1206
1207 // Give the policy a chance to intercept the key.
1208 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1209 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001210 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001211 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001212 sp<IBinder> focusedWindowToken =
1213 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1214 if (focusedWindowToken != nullptr) {
1215 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
1217 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001218 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 entry->refCount += 1;
1220 return false; // wait for the command to run
1221 } else {
1222 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1223 }
1224 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001225 if (*dropReason == DropReason::NOT_DROPPED) {
1226 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
1228 }
1229
1230 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001233 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1234 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001235 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 return true;
1237 }
1238
1239 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001240 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001241 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001243 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return false;
1245 }
1246
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001247 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001248 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 return true;
1250 }
1251
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001252 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001253 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
1255 // Dispatch the key.
1256 dispatchEventLocked(currentTime, entry, inputTargets);
1257 return true;
1258}
1259
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001262 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1264 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001265 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1266 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1267 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268#endif
1269}
1270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1272 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001273 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001275 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 entry->dispatchInProgress = true;
1277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001278 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 }
1280
1281 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001282 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001284 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1285 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 return true;
1287 }
1288
1289 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1290
1291 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001292 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
1294 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 if (isPointerEvent) {
1297 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001299 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 } else {
1302 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001304 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001306 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 return false;
1308 }
1309
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001310 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001311 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001312 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1313 return true;
1314 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001315 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001316 CancelationOptions::Mode mode(isPointerEvent
1317 ? CancelationOptions::CANCEL_POINTER_EVENTS
1318 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1319 CancelationOptions options(mode, "input event injection failed");
1320 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 return true;
1322 }
1323
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001324 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001325 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001327 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001328 std::unordered_map<int32_t, TouchState>::iterator it =
1329 mTouchStatesByDisplay.find(entry->displayId);
1330 if (it != mTouchStatesByDisplay.end()) {
1331 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001332 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001333 // The event has gone through these portal windows, so we add monitoring targets of
1334 // the corresponding displays as well.
1335 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001336 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001337 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001339 }
1340 }
1341 }
1342 }
1343
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 // Dispatch the motion.
1345 if (conflictingPointerActions) {
1346 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 synthesizeCancelationEventsForAllConnectionsLocked(options);
1349 }
1350 dispatchEventLocked(currentTime, entry, inputTargets);
1351 return true;
1352}
1353
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001354void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001356 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001357 ", policyFlags=0x%x, "
1358 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1359 "metaState=0x%x, buttonState=0x%x,"
1360 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001361 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1362 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1363 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001365 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 "x=%f, y=%f, pressure=%f, size=%f, "
1368 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1369 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001370 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1371 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1372 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1373 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1374 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1375 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1376 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1377 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1378 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1379 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381#endif
1382}
1383
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001384void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1385 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001386 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387#if DEBUG_DISPATCH_CYCLE
1388 ALOGD("dispatchEventToCurrentInputTargets");
1389#endif
1390
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001391 updateInteractionTokensLocked(*eventEntry, inputTargets);
1392
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1394
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001397 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001398 sp<Connection> connection =
1399 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001400 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001401 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001403 if (DEBUG_FOCUS) {
1404 ALOGD("Dropping event delivery to target with channel '%s' because it "
1405 "is no longer registered with the input dispatcher.",
1406 inputTarget.inputChannel->getName().c_str());
1407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 }
1409 }
1410}
1411
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001412void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1413 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1414 // If the policy decides to close the app, we will get a channel removal event via
1415 // unregisterInputChannel, and will clean up the connection that way. We are already not
1416 // sending new pointers to the connection when it blocked, but focused events will continue to
1417 // pile up.
1418 ALOGW("Canceling events for %s because it is unresponsive",
1419 connection->inputChannel->getName().c_str());
1420 if (connection->status == Connection::STATUS_NORMAL) {
1421 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1422 "application not responding");
1423 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425}
1426
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001427void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001428 if (DEBUG_FOCUS) {
1429 ALOGD("Resetting ANR timeouts.");
1430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431
1432 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001433 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001434 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435}
1436
Tiger Huang721e26f2018-07-24 22:26:19 +08001437/**
1438 * Get the display id that the given event should go to. If this event specifies a valid display id,
1439 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1440 * Focused display is the display that the user most recently interacted with.
1441 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001442int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001443 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001445 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1447 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001448 break;
1449 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001450 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001451 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1452 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 break;
1454 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001455 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001456 case EventEntry::Type::CONFIGURATION_CHANGED:
1457 case EventEntry::Type::DEVICE_RESET: {
1458 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001459 return ADISPLAY_ID_NONE;
1460 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001461 }
1462 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1463}
1464
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1466 const char* focusedWindowName) {
1467 if (mAnrTracker.empty()) {
1468 // already processed all events that we waited for
1469 mKeyIsWaitingForEventsTimeout = std::nullopt;
1470 return false;
1471 }
1472
1473 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1474 // Start the timer
1475 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1476 "focus to change",
1477 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001478 mKeyIsWaitingForEventsTimeout = currentTime +
1479 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1480 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001481 return true;
1482 }
1483
1484 // We still have pending events, and already started the timer
1485 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1486 return true; // Still waiting
1487 }
1488
1489 // Waited too long, and some connection still hasn't processed all motions
1490 // Just send the key to the focused window
1491 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1492 focusedWindowName);
1493 mKeyIsWaitingForEventsTimeout = std::nullopt;
1494 return false;
1495}
1496
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1498 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1499 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001500 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501
Tiger Huang721e26f2018-07-24 22:26:19 +08001502 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001503 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001504 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001505 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1506
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 // If there is no currently focused window and no focused application
1508 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001509 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1510 ALOGI("Dropping %s event because there is no focused window or focused application in "
1511 "display %" PRId32 ".",
1512 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001516 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1517 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1518 // start interacting with another application via touch (app switch). This code can be removed
1519 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1520 // an app is expected to have a focused window.
1521 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1522 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1523 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001524 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1525 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1526 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001527 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001528 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001529 ALOGW("Waiting because no window has focus but %s may eventually add a "
1530 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001531 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001532 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001534 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1535 // Already raised ANR. Drop the event
1536 ALOGE("Dropping %s event because there is no focused window",
1537 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001539 } else {
1540 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001541 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001542 }
1543 }
1544
1545 // we have a valid, non-null focused window
1546 resetNoFocusedWindowTimeoutLocked();
1547
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001550 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 }
1552
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001553 if (focusedWindowHandle->getInfo()->paused) {
1554 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001556 }
1557
1558 // If the event is a key event, then we must wait for all previous events to
1559 // complete before delivering it because previous events may have the
1560 // side-effect of transferring focus to a different window and we want to
1561 // ensure that the following keys are sent to the new window.
1562 //
1563 // Suppose the user touches a button in a window then immediately presses "A".
1564 // If the button causes a pop-up window to appear then we want to ensure that
1565 // the "A" key is delivered to the new pop-up window. This is because users
1566 // often anticipate pending UI changes when typing on a keyboard.
1567 // To obtain this behavior, we must serialize key events with respect to all
1568 // prior input events.
1569 if (entry.type == EventEntry::Type::KEY) {
1570 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1571 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 }
1575
1576 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001577 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001578 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1579 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580
1581 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583}
1584
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001585/**
1586 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1587 * that are currently unresponsive.
1588 */
1589std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1590 const std::vector<TouchedMonitor>& monitors) const {
1591 std::vector<TouchedMonitor> responsiveMonitors;
1592 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1593 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1594 sp<Connection> connection = getConnectionLocked(
1595 monitor.monitor.inputChannel->getConnectionToken());
1596 if (connection == nullptr) {
1597 ALOGE("Could not find connection for monitor %s",
1598 monitor.monitor.inputChannel->getName().c_str());
1599 return false;
1600 }
1601 if (!connection->responsive) {
1602 ALOGW("Unresponsive monitor %s will not get the new gesture",
1603 connection->inputChannel->getName().c_str());
1604 return false;
1605 }
1606 return true;
1607 });
1608 return responsiveMonitors;
1609}
1610
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1612 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1613 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 enum InjectionPermission {
1616 INJECTION_PERMISSION_UNKNOWN,
1617 INJECTION_PERMISSION_GRANTED,
1618 INJECTION_PERMISSION_DENIED
1619 };
1620
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 // For security reasons, we defer updating the touch state until we are sure that
1622 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 int32_t displayId = entry.displayId;
1624 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1626
1627 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001628 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001630 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1631 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001633 // Copy current touch state into tempTouchState.
1634 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1635 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001636 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001637 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001638 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1639 mTouchStatesByDisplay.find(displayId);
1640 if (oldStateIt != mTouchStatesByDisplay.end()) {
1641 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001642 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001643 }
1644
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001645 bool isSplit = tempTouchState.split;
1646 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1647 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1648 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1650 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1651 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1652 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1653 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 bool wrongDevice = false;
1656 if (newGesture) {
1657 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001658 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001659 ALOGI("Dropping event because a pointer for a different device is already down "
1660 "in display %" PRId32,
1661 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001662 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001663 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 switchedDevice = false;
1665 wrongDevice = true;
1666 goto Failed;
1667 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001668 tempTouchState.reset();
1669 tempTouchState.down = down;
1670 tempTouchState.deviceId = entry.deviceId;
1671 tempTouchState.source = entry.source;
1672 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001674 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001675 ALOGI("Dropping move event because a pointer for a different device is already active "
1676 "in display %" PRId32,
1677 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001678 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001679 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001680 switchedDevice = false;
1681 wrongDevice = true;
1682 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1686 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1687
Garfield Tan00f511d2019-06-12 16:55:40 -07001688 int32_t x;
1689 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001691 // Always dispatch mouse events to cursor position.
1692 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 x = int32_t(entry.xCursorPosition);
1694 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001695 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1697 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001698 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001699 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001700 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001701 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1702 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001703
1704 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001705 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001706 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 if (newTouchedWindowHandle != nullptr &&
1710 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001711 // New window supports splitting, but we should never split mouse events.
1712 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 } else if (isSplit) {
1714 // New window does not support splitting but we have already split events.
1715 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718
1719 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001722 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 }
1724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1726 ALOGI("Not sending touch event to %s because it is paused",
1727 newTouchedWindowHandle->getName().c_str());
1728 newTouchedWindowHandle = nullptr;
1729 }
1730
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001731 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001733 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1734 if (!isResponsive) {
1735 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1737 newTouchedWindowHandle = nullptr;
1738 }
1739 }
1740
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001741 // Drop events that can't be trusted due to occlusion
1742 if (newTouchedWindowHandle != nullptr &&
1743 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1744 TouchOcclusionInfo occlusionInfo =
1745 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
1746 // The order of the operands in the 'if' below is important because even if the feature
1747 // is not BLOCK we want isTouchTrustedLocked() to execute in order to log details to
1748 // logcat.
1749 if (!isTouchTrustedLocked(occlusionInfo) &&
1750 mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1751 ALOGW("Dropping untrusted touch event due to %s/%d",
1752 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1753 newTouchedWindowHandle = nullptr;
1754 }
1755 }
1756
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 // Also don't send the new touch event to unresponsive gesture monitors
1758 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1759
Michael Wright3dd60e22019-03-27 22:06:44 +00001760 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1761 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 "(%d, %d) in display %" PRId32 ".",
1763 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001764 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001765 goto Failed;
1766 }
1767
1768 if (newTouchedWindowHandle != nullptr) {
1769 // Set target flags.
1770 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1771 if (isSplit) {
1772 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001774 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1775 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1776 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1777 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1778 }
1779
1780 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001781 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1782 newHoverWindowHandle = nullptr;
1783 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001784 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001785 }
1786
1787 // Update the temporary touch state.
1788 BitSet32 pointerIds;
1789 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001791 pointerIds.markBit(pointerId);
1792 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001793 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001796 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 } else {
1798 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1799
1800 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001801 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001802 if (DEBUG_FOCUS) {
1803 ALOGD("Dropping event because the pointer is not down or we previously "
1804 "dropped the pointer down event in display %" PRId32,
1805 displayId);
1806 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 goto Failed;
1809 }
1810
1811 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1815 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001818 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001819 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1821 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1824 oldTouchedWindowHandle->getName().c_str(),
1825 newTouchedWindowHandle->getName().c_str(), displayId);
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001828 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1829 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1830 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
1832 // Make a slippery entrance into the new window.
1833 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1834 isSplit = true;
1835 }
1836
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 int32_t targetFlags =
1838 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 if (isSplit) {
1840 targetFlags |= InputTarget::FLAG_SPLIT;
1841 }
1842 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1843 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1844 }
1845
1846 BitSet32 pointerIds;
1847 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001848 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852 }
1853 }
1854
1855 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001856 // Let the previous window know that the hover sequence is over, unless we already did it
1857 // when dispatching it as is to newTouchedWindowHandle.
1858 if (mLastHoverWindowHandle != nullptr &&
1859 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1860 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861#if DEBUG_HOVER
1862 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1866 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
1868
Garfield Tandf26e862020-07-01 20:18:19 -07001869 // Let the new window know that the hover sequence is starting, unless we already did it
1870 // when dispatching it as is to newTouchedWindowHandle.
1871 if (newHoverWindowHandle != nullptr &&
1872 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1873 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874#if DEBUG_HOVER
1875 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001876 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001878 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1879 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1880 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882 }
1883
1884 // Check permission to inject into all touched foreground windows and ensure there
1885 // is at least one touched foreground window.
1886 {
1887 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1890 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 injectionPermission = INJECTION_PERMISSION_DENIED;
1894 goto Failed;
1895 }
1896 }
1897 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001899 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001900 ALOGI("Dropping event because there is no touched foreground window in display "
1901 "%" PRId32 " or gesture monitor to receive it.",
1902 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 goto Failed;
1905 }
1906
1907 // Permission granted to injection into all touched foreground windows.
1908 injectionPermission = INJECTION_PERMISSION_GRANTED;
1909 }
1910
1911 // Check whether windows listening for outside touches are owned by the same UID. If it is
1912 // set the policy flag that we will not reveal coordinate information to this window.
1913 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1914 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 if (foregroundWindowHandle) {
1917 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001919 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1920 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1921 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1923 InputTarget::FLAG_ZERO_COORDS,
1924 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927 }
1928 }
1929 }
1930
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 // If this is the first pointer going down and the touched window has a wallpaper
1932 // then also add the touched wallpaper windows so they are locked in for the duration
1933 // of the touch gesture.
1934 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1935 // engine only supports touch events. We would need to add a mechanism similar
1936 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1937 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1938 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001940 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001941 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001942 getWindowHandlesLocked(displayId);
1943 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001945 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001946 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001948 .addOrUpdateWindow(windowHandle,
1949 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1950 InputTarget::
1951 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1952 InputTarget::FLAG_DISPATCH_AS_IS,
1953 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
1955 }
1956 }
1957 }
1958
1959 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001967 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001968 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 }
1971
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // Drop the outside or hover touch windows since we will not care about them
1973 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975
1976Failed:
1977 // Check injection permission once and for all.
1978 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001979 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 injectionPermission = INJECTION_PERMISSION_GRANTED;
1981 } else {
1982 injectionPermission = INJECTION_PERMISSION_DENIED;
1983 }
1984 }
1985
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001986 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1987 return injectionResult;
1988 }
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 if (!wrongDevice) {
1992 if (switchedDevice) {
1993 if (DEBUG_FOCUS) {
1994 ALOGD("Conflicting pointer actions: Switched to a different device.");
1995 }
1996 *outConflictingPointerActions = true;
1997 }
1998
1999 if (isHoverAction) {
2000 // Started hovering, therefore no longer down.
2001 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002002 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002003 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2004 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 *outConflictingPointerActions = true;
2007 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002008 tempTouchState.reset();
2009 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2010 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2011 tempTouchState.deviceId = entry.deviceId;
2012 tempTouchState.source = entry.source;
2013 tempTouchState.displayId = displayId;
2014 }
2015 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2016 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2017 // All pointers up or canceled.
2018 tempTouchState.reset();
2019 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2020 // First pointer went down.
2021 if (oldState && oldState->down) {
2022 if (DEBUG_FOCUS) {
2023 ALOGD("Conflicting pointer actions: Down received while already down.");
2024 }
2025 *outConflictingPointerActions = true;
2026 }
2027 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2028 // One pointer went up.
2029 if (isSplit) {
2030 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2031 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002033 for (size_t i = 0; i < tempTouchState.windows.size();) {
2034 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2035 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2036 touchedWindow.pointerIds.clearBit(pointerId);
2037 if (touchedWindow.pointerIds.isEmpty()) {
2038 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2039 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002042 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002044 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002045 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002046
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002047 // Save changes unless the action was scroll in which case the temporary touch
2048 // state was only valid for this one action.
2049 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2050 if (tempTouchState.displayId >= 0) {
2051 mTouchStatesByDisplay[displayId] = tempTouchState;
2052 } else {
2053 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002057 // Update hover state.
2058 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 }
2060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 return injectionResult;
2062}
2063
2064void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002065 int32_t targetFlags, BitSet32 pointerIds,
2066 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002067 std::vector<InputTarget>::iterator it =
2068 std::find_if(inputTargets.begin(), inputTargets.end(),
2069 [&windowHandle](const InputTarget& inputTarget) {
2070 return inputTarget.inputChannel->getConnectionToken() ==
2071 windowHandle->getToken();
2072 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002073
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002074 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002075
2076 if (it == inputTargets.end()) {
2077 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002078 std::shared_ptr<InputChannel> inputChannel =
2079 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002080 if (inputChannel == nullptr) {
2081 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2082 return;
2083 }
2084 inputTarget.inputChannel = inputChannel;
2085 inputTarget.flags = targetFlags;
2086 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2087 inputTargets.push_back(inputTarget);
2088 it = inputTargets.end() - 1;
2089 }
2090
2091 ALOG_ASSERT(it->flags == targetFlags);
2092 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2093
chaviw1ff3d1e2020-07-01 15:53:47 -07002094 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095}
2096
Michael Wright3dd60e22019-03-27 22:06:44 +00002097void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 int32_t displayId, float xOffset,
2099 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2101 mGlobalMonitorsByDisplay.find(displayId);
2102
2103 if (it != mGlobalMonitorsByDisplay.end()) {
2104 const std::vector<Monitor>& monitors = it->second;
2105 for (const Monitor& monitor : monitors) {
2106 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
2109}
2110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002111void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2112 float yOffset,
2113 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002114 InputTarget target;
2115 target.inputChannel = monitor.inputChannel;
2116 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002117 ui::Transform t;
2118 t.set(xOffset, yOffset);
2119 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002120 inputTargets.push_back(target);
2121}
2122
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 const InjectionState* injectionState) {
2125 if (injectionState &&
2126 (windowHandle == nullptr ||
2127 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2128 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002129 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 "owned by uid %d",
2132 injectionState->injectorPid, injectionState->injectorUid,
2133 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 } else {
2135 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138 return false;
2139 }
2140 return true;
2141}
2142
Robert Carrc9bf1d32020-04-13 17:21:08 -07002143/**
2144 * Indicate whether one window handle should be considered as obscuring
2145 * another window handle. We only check a few preconditions. Actually
2146 * checking the bounds is left to the caller.
2147 */
2148static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2149 const sp<InputWindowHandle>& otherHandle) {
2150 // Compare by token so cloned layers aren't counted
2151 if (haveSameToken(windowHandle, otherHandle)) {
2152 return false;
2153 }
2154 auto info = windowHandle->getInfo();
2155 auto otherInfo = otherHandle->getInfo();
2156 if (!otherInfo->visible) {
2157 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002158 } else if (info->ownerUid == otherInfo->ownerUid) {
2159 // If ownerUid is the same we don't generate occlusion events as there
2160 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002161 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002162 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002163 return false;
2164 } else if (otherInfo->displayId != info->displayId) {
2165 return false;
2166 }
2167 return true;
2168}
2169
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002170/**
2171 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2172 * untrusted, one should check:
2173 *
2174 * 1. If result.hasBlockingOcclusion is true.
2175 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2176 * BLOCK_UNTRUSTED.
2177 *
2178 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2179 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2180 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2181 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2182 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2183 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2184 *
2185 * If neither of those is true, then it means the touch can be allowed.
2186 */
2187InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2188 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2189 int32_t displayId = windowHandle->getInfo()->displayId;
2190 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2191 TouchOcclusionInfo info;
2192 info.hasBlockingOcclusion = false;
2193 info.obscuringOpacity = 0;
2194 info.obscuringUid = -1;
2195 std::map<int32_t, float> opacityByUid;
2196 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2197 if (windowHandle == otherHandle) {
2198 break; // All future windows are below us. Exit early.
2199 }
2200 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2201 if (canBeObscuredBy(windowHandle, otherHandle) &&
2202 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2203 otherInfo->frameContainsPoint(x, y)) {
2204 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2205 // we perform the checks below to see if the touch can be propagated or not based on the
2206 // window's touch occlusion mode
2207 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2208 info.hasBlockingOcclusion = true;
2209 info.obscuringUid = otherInfo->ownerUid;
2210 info.obscuringPackage = otherInfo->packageName;
2211 break;
2212 }
2213 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2214 uint32_t uid = otherInfo->ownerUid;
2215 float opacity =
2216 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2217 // Given windows A and B:
2218 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2219 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2220 opacityByUid[uid] = opacity;
2221 if (opacity > info.obscuringOpacity) {
2222 info.obscuringOpacity = opacity;
2223 info.obscuringUid = uid;
2224 info.obscuringPackage = otherInfo->packageName;
2225 }
2226 }
2227 }
2228 }
2229 return info;
2230}
2231
2232bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2233 if (occlusionInfo.hasBlockingOcclusion) {
2234 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2235 occlusionInfo.obscuringUid);
2236 return false;
2237 }
2238 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2239 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2240 "%.2f, maximum allowed = %.2f)",
2241 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2242 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2243 return false;
2244 }
2245 return true;
2246}
2247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2249 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002251 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002252 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002253 if (windowHandle == otherHandle) {
2254 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002257 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002258 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 return true;
2260 }
2261 }
2262 return false;
2263}
2264
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002265bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2266 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002267 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002268 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002269 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002270 if (windowHandle == otherHandle) {
2271 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002272 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002273 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002274 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002275 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002276 return true;
2277 }
2278 }
2279 return false;
2280}
2281
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002282std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002283 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002285 if (applicationHandle != nullptr) {
2286 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002287 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 } else {
2289 return applicationHandle->getName();
2290 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002291 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002292 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002294 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296}
2297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002298void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002299 if (eventEntry.type == EventEntry::Type::FOCUS) {
2300 // Focus events are passed to apps, but do not represent user activity.
2301 return;
2302 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002303 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002304 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002305 if (focusedWindowHandle != nullptr) {
2306 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002307 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002309 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310#endif
2311 return;
2312 }
2313 }
2314
2315 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002316 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002317 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002318 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2319 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320 return;
2321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002323 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 eventType = USER_ACTIVITY_EVENT_TOUCH;
2325 }
2326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002328 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002329 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2330 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 return;
2332 }
2333 eventType = USER_ACTIVITY_EVENT_BUTTON;
2334 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002336 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002337 case EventEntry::Type::CONFIGURATION_CHANGED:
2338 case EventEntry::Type::DEVICE_RESET: {
2339 LOG_ALWAYS_FATAL("%s events are not user activity",
2340 EventEntry::typeToString(eventEntry.type));
2341 break;
2342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002345 std::unique_ptr<CommandEntry> commandEntry =
2346 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002347 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002349 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350}
2351
2352void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 const sp<Connection>& connection,
2354 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002355 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002356 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002358 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002359 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002360 ATRACE_NAME(message.c_str());
2361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362#if DEBUG_DISPATCH_CYCLE
2363 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002364 "globalScaleFactor=%f, pointerIds=0x%x %s",
2365 connection->getInputChannelName().c_str(), inputTarget.flags,
2366 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2367 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
2369
2370 // Skip this event if the connection status is not normal.
2371 // We don't want to enqueue additional outbound events if the connection is broken.
2372 if (connection->status != Connection::STATUS_NORMAL) {
2373#if DEBUG_DISPATCH_CYCLE
2374 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376#endif
2377 return;
2378 }
2379
2380 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002381 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2382 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2383 "Entry type %s should not have FLAG_SPLIT",
2384 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002386 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002387 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002389 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 if (!splitMotionEntry) {
2391 return; // split event was dropped
2392 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002393 if (DEBUG_FOCUS) {
2394 ALOGD("channel '%s' ~ Split motion event.",
2395 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002396 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002397 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 splitMotionEntry->release();
2400 return;
2401 }
2402 }
2403
2404 // Not splitting. Enqueue dispatch entries for the event as is.
2405 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2406}
2407
2408void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002409 const sp<Connection>& connection,
2410 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002411 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002412 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002414 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002415 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 ATRACE_NAME(message.c_str());
2417 }
2418
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002419 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
2421 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002422 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002424 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002425 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002426 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002428 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002430 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002432 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434
2435 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002436 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 startDispatchCycleLocked(currentTime, connection);
2438 }
2439}
2440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002441void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2442 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002443 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002444 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002445 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002446 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2447 connection->getInputChannelName().c_str(),
2448 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002449 ATRACE_NAME(message.c_str());
2450 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002451 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 if (!(inputTargetFlags & dispatchMode)) {
2453 return;
2454 }
2455 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2456
2457 // This is a new event.
2458 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002459 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002460 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002462 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2463 // different EventEntry than what was passed in.
2464 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002466 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002467 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002468 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002469 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002470 dispatchEntry->resolvedAction = keyEntry.action;
2471 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2474 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2477 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479 return; // skip the inconsistent event
2480 }
2481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002484 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002485 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002486 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2487 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2488 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2489 static_cast<int32_t>(IdGenerator::Source::OTHER);
2490 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2492 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2493 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2494 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2495 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2496 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2497 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2498 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2499 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2500 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2501 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002502 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002503 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 }
2505 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002506 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2507 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2510 "event",
2511 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002516 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2518 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2519 }
2520 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2521 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2525 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2528 "event",
2529 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 return; // skip the inconsistent event
2532 }
2533
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002534 dispatchEntry->resolvedEventId =
2535 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2536 ? mIdGenerator.nextId()
2537 : motionEntry.id;
2538 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2539 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2540 ") to MotionEvent(id=0x%" PRIx32 ").",
2541 motionEntry.id, dispatchEntry->resolvedEventId);
2542 ATRACE_NAME(message.c_str());
2543 }
2544
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002545 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002546 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547
2548 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002550 case EventEntry::Type::FOCUS: {
2551 break;
2552 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002553 case EventEntry::Type::CONFIGURATION_CHANGED:
2554 case EventEntry::Type::DEVICE_RESET: {
2555 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002556 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002557 break;
2558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560
2561 // Remember that we are waiting for this dispatch to complete.
2562 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002563 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
2565
2566 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002567 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002568 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002569}
2570
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002571/**
2572 * This function is purely for debugging. It helps us understand where the user interaction
2573 * was taking place. For example, if user is touching launcher, we will see a log that user
2574 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2575 * We will see both launcher and wallpaper in that list.
2576 * Once the interaction with a particular set of connections starts, no new logs will be printed
2577 * until the set of interacted connections changes.
2578 *
2579 * The following items are skipped, to reduce the logspam:
2580 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2581 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2582 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2583 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2584 * Both of those ACTION_UP events would not be logged
2585 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2586 * will not be logged. This is omitted to reduce the amount of data printed.
2587 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2588 * gesture monitor is the only connection receiving the remainder of the gesture.
2589 */
2590void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2591 const std::vector<InputTarget>& targets) {
2592 // Skip ACTION_UP events, and all events other than keys and motions
2593 if (entry.type == EventEntry::Type::KEY) {
2594 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2595 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2596 return;
2597 }
2598 } else if (entry.type == EventEntry::Type::MOTION) {
2599 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2600 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2601 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2602 return;
2603 }
2604 } else {
2605 return; // Not a key or a motion
2606 }
2607
2608 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2609 std::vector<sp<Connection>> newConnections;
2610 for (const InputTarget& target : targets) {
2611 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2612 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2613 continue; // Skip windows that receive ACTION_OUTSIDE
2614 }
2615
2616 sp<IBinder> token = target.inputChannel->getConnectionToken();
2617 sp<Connection> connection = getConnectionLocked(token);
2618 if (connection == nullptr || connection->monitor) {
2619 continue; // We only need to keep track of the non-monitor connections.
2620 }
2621 newConnectionTokens.insert(std::move(token));
2622 newConnections.emplace_back(connection);
2623 }
2624 if (newConnectionTokens == mInteractionConnectionTokens) {
2625 return; // no change
2626 }
2627 mInteractionConnectionTokens = newConnectionTokens;
2628
2629 std::string windowList;
2630 for (const sp<Connection>& connection : newConnections) {
2631 windowList += connection->getWindowName() + ", ";
2632 }
2633 std::string message = "Interaction with windows: " + windowList;
2634 if (windowList.empty()) {
2635 message += "<none>";
2636 }
2637 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2638}
2639
chaviwfd6d3512019-03-25 13:23:49 -07002640void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002641 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002642 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002643 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2644 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002645 return;
2646 }
2647
Vishnu Nairad321cd2020-08-20 16:40:21 -07002648 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2649 if (focusedToken == token) {
2650 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002651 return;
2652 }
2653
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002654 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2655 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002656 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002657 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658}
2659
2660void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002662 if (ATRACE_ENABLED()) {
2663 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002665 ATRACE_NAME(message.c_str());
2666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669#endif
2670
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002671 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2672 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002674 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002675 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002676 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677
2678 // Publish the event.
2679 status_t status;
2680 EventEntry* eventEntry = dispatchEntry->eventEntry;
2681 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002682 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002683 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2684 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002686 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002687 status =
2688 connection->inputPublisher
2689 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2690 keyEntry->deviceId, keyEntry->source,
2691 keyEntry->displayId, std::move(hmac),
2692 dispatchEntry->resolvedAction,
2693 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2694 keyEntry->scanCode, keyEntry->metaState,
2695 keyEntry->repeatCount, keyEntry->downTime,
2696 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 }
2699
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002700 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703 PointerCoords scaledCoords[MAX_POINTERS];
2704 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2705
chaviw82357092020-01-28 13:13:06 -08002706 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2708 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2709 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002710 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2712 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002713 // Don't apply window scale here since we don't want scale to affect raw
2714 // coordinates. The scale will be sent back to the client and applied
2715 // later when requesting relative coordinates.
2716 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2717 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 }
2719 usingCoords = scaledCoords;
2720 }
2721 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 // We don't want the dispatch target to know.
2723 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2724 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2725 scaledCoords[i].clear();
2726 }
2727 usingCoords = scaledCoords;
2728 }
2729 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002730
2731 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732
2733 // Publish the motion event.
2734 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002735 .publishMotionEvent(dispatchEntry->seq,
2736 dispatchEntry->resolvedEventId,
2737 motionEntry->deviceId, motionEntry->source,
2738 motionEntry->displayId, std::move(hmac),
2739 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 motionEntry->actionButton,
2741 dispatchEntry->resolvedFlags,
2742 motionEntry->edgeFlags, motionEntry->metaState,
2743 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002744 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002745 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002746 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 motionEntry->yPrecision,
2748 motionEntry->xCursorPosition,
2749 motionEntry->yCursorPosition,
2750 motionEntry->downTime, motionEntry->eventTime,
2751 motionEntry->pointerCount,
2752 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002753 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002754 break;
2755 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002756 case EventEntry::Type::FOCUS: {
2757 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2758 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002759 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002760 focusEntry->hasFocus,
2761 mInTouchMode);
2762 break;
2763 }
2764
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002765 case EventEntry::Type::CONFIGURATION_CHANGED:
2766 case EventEntry::Type::DEVICE_RESET: {
2767 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2768 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
2772
2773 // Check the result.
2774 if (status) {
2775 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002776 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 "This is unexpected because the wait queue is empty, so the pipe "
2779 "should be empty and we shouldn't have any problems writing an "
2780 "event to it, status=%d",
2781 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2783 } else {
2784 // Pipe is full and we are waiting for the app to finish process some events
2785 // before sending more events to it.
2786#if DEBUG_DISPATCH_CYCLE
2787 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788 "waiting for the application to catch up",
2789 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 }
2792 } else {
2793 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 "status=%d",
2795 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2797 }
2798 return;
2799 }
2800
2801 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002802 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2803 connection->outboundQueue.end(),
2804 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002805 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002806 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002807 if (connection->responsive) {
2808 mAnrTracker.insert(dispatchEntry->timeoutTime,
2809 connection->inputChannel->getConnectionToken());
2810 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002811 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813}
2814
chaviw09c8d2d2020-08-24 15:48:26 -07002815std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2816 size_t size;
2817 switch (event.type) {
2818 case VerifiedInputEvent::Type::KEY: {
2819 size = sizeof(VerifiedKeyEvent);
2820 break;
2821 }
2822 case VerifiedInputEvent::Type::MOTION: {
2823 size = sizeof(VerifiedMotionEvent);
2824 break;
2825 }
2826 }
2827 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2828 return mHmacKeyManager.sign(start, size);
2829}
2830
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002831const std::array<uint8_t, 32> InputDispatcher::getSignature(
2832 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2833 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2834 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2835 // Only sign events up and down events as the purely move events
2836 // are tied to their up/down counterparts so signing would be redundant.
2837 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2838 verifiedEvent.actionMasked = actionMasked;
2839 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002840 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002841 }
2842 return INVALID_HMAC;
2843}
2844
2845const std::array<uint8_t, 32> InputDispatcher::getSignature(
2846 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2847 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2848 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2849 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002850 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002851}
2852
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 const sp<Connection>& connection, uint32_t seq,
2855 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856#if DEBUG_DISPATCH_CYCLE
2857 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002858 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859#endif
2860
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 if (connection->status == Connection::STATUS_BROKEN ||
2862 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 return;
2864 }
2865
2866 // Notify other system components and prepare to start the next dispatch cycle.
2867 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2868}
2869
2870void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 const sp<Connection>& connection,
2872 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873#if DEBUG_DISPATCH_CYCLE
2874 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876#endif
2877
2878 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002879 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002880 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002881 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002882 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
2884 // The connection appears to be unrecoverably broken.
2885 // Ignore already broken or zombie connections.
2886 if (connection->status == Connection::STATUS_NORMAL) {
2887 connection->status = Connection::STATUS_BROKEN;
2888
2889 if (notify) {
2890 // Notify other system components.
2891 onDispatchCycleBrokenLocked(currentTime, connection);
2892 }
2893 }
2894}
2895
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002896void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2897 while (!queue.empty()) {
2898 DispatchEntry* dispatchEntry = queue.front();
2899 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002900 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
2902}
2903
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002904void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002906 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
2908 delete dispatchEntry;
2909}
2910
2911int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2912 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2913
2914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002915 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002917 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 "fd=%d, events=0x%x",
2920 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return 0; // remove the callback
2922 }
2923
2924 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002925 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2927 if (!(events & ALOOPER_EVENT_INPUT)) {
2928 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 "events=0x%x",
2930 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 return 1;
2932 }
2933
2934 nsecs_t currentTime = now();
2935 bool gotOne = false;
2936 status_t status;
2937 for (;;) {
2938 uint32_t seq;
2939 bool handled;
2940 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2941 if (status) {
2942 break;
2943 }
2944 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2945 gotOne = true;
2946 }
2947 if (gotOne) {
2948 d->runCommandsLockedInterruptible();
2949 if (status == WOULD_BLOCK) {
2950 return 1;
2951 }
2952 }
2953
2954 notify = status != DEAD_OBJECT || !connection->monitor;
2955 if (notify) {
2956 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
2959 } else {
2960 // Monitor channels are never explicitly unregistered.
2961 // We do it automatically when the remote endpoint is closed so don't warn
2962 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002963 const bool stillHaveWindowHandle =
2964 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2965 nullptr;
2966 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 if (notify) {
2968 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 "events=0x%x",
2970 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 }
2972 }
2973
Garfield Tan15601662020-09-22 15:32:38 -07002974 // Remove the channel.
2975 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978}
2979
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002982 for (const auto& pair : mConnectionsByFd) {
2983 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985}
2986
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002988 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002989 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2990 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2991}
2992
2993void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2994 const CancelationOptions& options,
2995 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2996 for (const auto& it : monitorsByDisplay) {
2997 const std::vector<Monitor>& monitors = it.second;
2998 for (const Monitor& monitor : monitors) {
2999 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003000 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003001 }
3002}
3003
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003005 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003006 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003007 if (connection == nullptr) {
3008 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003010
3011 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012}
3013
3014void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3015 const sp<Connection>& connection, const CancelationOptions& options) {
3016 if (connection->status == Connection::STATUS_BROKEN) {
3017 return;
3018 }
3019
3020 nsecs_t currentTime = now();
3021
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003022 std::vector<EventEntry*> cancelationEvents =
3023 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003025 if (cancelationEvents.empty()) {
3026 return;
3027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003029 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3030 "with reality: %s, mode=%d.",
3031 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3032 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003034
3035 InputTarget target;
3036 sp<InputWindowHandle> windowHandle =
3037 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3038 if (windowHandle != nullptr) {
3039 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003040 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003041 target.globalScaleFactor = windowInfo->globalScaleFactor;
3042 }
3043 target.inputChannel = connection->inputChannel;
3044 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3045
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003046 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3047 EventEntry* cancelationEventEntry = cancelationEvents[i];
3048 switch (cancelationEventEntry->type) {
3049 case EventEntry::Type::KEY: {
3050 logOutboundKeyDetails("cancel - ",
3051 static_cast<const KeyEntry&>(*cancelationEventEntry));
3052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003054 case EventEntry::Type::MOTION: {
3055 logOutboundMotionDetails("cancel - ",
3056 static_cast<const MotionEntry&>(*cancelationEventEntry));
3057 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003059 case EventEntry::Type::FOCUS: {
3060 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3061 break;
3062 }
3063 case EventEntry::Type::CONFIGURATION_CHANGED:
3064 case EventEntry::Type::DEVICE_RESET: {
3065 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3066 EventEntry::typeToString(cancelationEventEntry->type));
3067 break;
3068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 }
3070
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003071 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3072 target, InputTarget::FLAG_DISPATCH_AS_IS);
3073
3074 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003076
3077 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078}
3079
Svet Ganov5d3bc372020-01-26 23:11:07 -08003080void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3081 const sp<Connection>& connection) {
3082 if (connection->status == Connection::STATUS_BROKEN) {
3083 return;
3084 }
3085
3086 nsecs_t currentTime = now();
3087
3088 std::vector<EventEntry*> downEvents =
3089 connection->inputState.synthesizePointerDownEvents(currentTime);
3090
3091 if (downEvents.empty()) {
3092 return;
3093 }
3094
3095#if DEBUG_OUTBOUND_EVENT_DETAILS
3096 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3097 connection->getInputChannelName().c_str(), downEvents.size());
3098#endif
3099
3100 InputTarget target;
3101 sp<InputWindowHandle> windowHandle =
3102 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3103 if (windowHandle != nullptr) {
3104 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003105 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003106 target.globalScaleFactor = windowInfo->globalScaleFactor;
3107 }
3108 target.inputChannel = connection->inputChannel;
3109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3110
3111 for (EventEntry* downEventEntry : downEvents) {
3112 switch (downEventEntry->type) {
3113 case EventEntry::Type::MOTION: {
3114 logOutboundMotionDetails("down - ",
3115 static_cast<const MotionEntry&>(*downEventEntry));
3116 break;
3117 }
3118
3119 case EventEntry::Type::KEY:
3120 case EventEntry::Type::FOCUS:
3121 case EventEntry::Type::CONFIGURATION_CHANGED:
3122 case EventEntry::Type::DEVICE_RESET: {
3123 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3124 EventEntry::typeToString(downEventEntry->type));
3125 break;
3126 }
3127 }
3128
3129 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3130 target, InputTarget::FLAG_DISPATCH_AS_IS);
3131
3132 downEventEntry->release();
3133 }
3134
3135 startDispatchCycleLocked(currentTime, connection);
3136}
3137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003139 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 ALOG_ASSERT(pointerIds.value != 0);
3141
3142 uint32_t splitPointerIndexMap[MAX_POINTERS];
3143 PointerProperties splitPointerProperties[MAX_POINTERS];
3144 PointerCoords splitPointerCoords[MAX_POINTERS];
3145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003146 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 uint32_t splitPointerCount = 0;
3148
3149 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 uint32_t pointerId = uint32_t(pointerProperties.id);
3154 if (pointerIds.hasBit(pointerId)) {
3155 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3156 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3157 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003158 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 splitPointerCount += 1;
3160 }
3161 }
3162
3163 if (splitPointerCount != pointerIds.count()) {
3164 // This is bad. We are missing some of the pointers that we expected to deliver.
3165 // Most likely this indicates that we received an ACTION_MOVE events that has
3166 // different pointer ids than we expected based on the previous ACTION_DOWN
3167 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3168 // in this way.
3169 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 "we expected there to be %d pointers. This probably means we received "
3171 "a broken sequence of pointer ids from the input device.",
3172 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003173 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
3175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3179 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3181 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 uint32_t pointerId = uint32_t(pointerProperties.id);
3184 if (pointerIds.hasBit(pointerId)) {
3185 if (pointerIds.count() == 1) {
3186 // The first/last pointer went down/up.
3187 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 ? AMOTION_EVENT_ACTION_DOWN
3189 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 } else {
3191 // A secondary pointer went down/up.
3192 uint32_t splitPointerIndex = 0;
3193 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3194 splitPointerIndex += 1;
3195 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 action = maskedAction |
3197 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199 } else {
3200 // An unrelated pointer changed.
3201 action = AMOTION_EVENT_ACTION_MOVE;
3202 }
3203 }
3204
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003205 int32_t newId = mIdGenerator.nextId();
3206 if (ATRACE_ENABLED()) {
3207 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3208 ") to MotionEvent(id=0x%" PRIx32 ").",
3209 originalMotionEntry.id, newId);
3210 ATRACE_NAME(message.c_str());
3211 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003212 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003213 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3214 originalMotionEntry.source, originalMotionEntry.displayId,
3215 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 originalMotionEntry.actionButton, originalMotionEntry.flags,
3217 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3218 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3219 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3220 originalMotionEntry.xCursorPosition,
3221 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003222 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003224 if (originalMotionEntry.injectionState) {
3225 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 splitMotionEntry->injectionState->refCount += 1;
3227 }
3228
3229 return splitMotionEntry;
3230}
3231
3232void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3233#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003234 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235#endif
3236
3237 bool needWake;
3238 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003239 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240
Prabir Pradhan42611e02018-11-27 14:04:02 -08003241 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003242 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 needWake = enqueueInboundEventLocked(newEntry);
3244 } // release lock
3245
3246 if (needWake) {
3247 mLooper->wake();
3248 }
3249}
3250
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003251/**
3252 * If one of the meta shortcuts is detected, process them here:
3253 * Meta + Backspace -> generate BACK
3254 * Meta + Enter -> generate HOME
3255 * This will potentially overwrite keyCode and metaState.
3256 */
3257void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003259 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3260 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3261 if (keyCode == AKEYCODE_DEL) {
3262 newKeyCode = AKEYCODE_BACK;
3263 } else if (keyCode == AKEYCODE_ENTER) {
3264 newKeyCode = AKEYCODE_HOME;
3265 }
3266 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003267 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003268 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003269 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003270 keyCode = newKeyCode;
3271 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3272 }
3273 } else if (action == AKEY_EVENT_ACTION_UP) {
3274 // In order to maintain a consistent stream of up and down events, check to see if the key
3275 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3276 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003277 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003278 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003279 auto replacementIt = mReplacedKeys.find(replacement);
3280 if (replacementIt != mReplacedKeys.end()) {
3281 keyCode = replacementIt->second;
3282 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003283 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3284 }
3285 }
3286}
3287
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3289#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3291 "policyFlags=0x%x, action=0x%x, "
3292 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3293 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3294 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3295 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296#endif
3297 if (!validateKeyEvent(args->action)) {
3298 return;
3299 }
3300
3301 uint32_t policyFlags = args->policyFlags;
3302 int32_t flags = args->flags;
3303 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003304 // InputDispatcher tracks and generates key repeats on behalf of
3305 // whatever notifies it, so repeatCount should always be set to 0
3306 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3308 policyFlags |= POLICY_FLAG_VIRTUAL;
3309 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 if (policyFlags & POLICY_FLAG_FUNCTION) {
3312 metaState |= AMETA_FUNCTION_ON;
3313 }
3314
3315 policyFlags |= POLICY_FLAG_TRUSTED;
3316
Michael Wright78f24442014-08-06 15:55:28 -07003317 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003318 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003319
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003321 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003322 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3323 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Michael Wright2b3c3302018-03-02 17:19:13 +00003325 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003327 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3328 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 bool needWake;
3333 { // acquire lock
3334 mLock.lock();
3335
3336 if (shouldSendKeyToInputFilterLocked(args)) {
3337 mLock.unlock();
3338
3339 policyFlags |= POLICY_FLAG_FILTERED;
3340 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3341 return; // event was consumed by the filter
3342 }
3343
3344 mLock.lock();
3345 }
3346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003348 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 args->displayId, policyFlags, args->action, flags, keyCode,
3350 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
3352 needWake = enqueueInboundEventLocked(newEntry);
3353 mLock.unlock();
3354 } // release lock
3355
3356 if (needWake) {
3357 mLooper->wake();
3358 }
3359}
3360
3361bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3362 return mInputFilterEnabled;
3363}
3364
3365void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3366#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003367 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3368 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003369 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3370 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003371 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003372 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3373 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3374 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3375 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 for (uint32_t i = 0; i < args->pointerCount; i++) {
3377 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 "x=%f, y=%f, pressure=%f, size=%f, "
3379 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3380 "orientation=%f",
3381 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3382 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3383 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3384 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3385 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3386 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3387 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3388 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3389 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3390 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
3392#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003393 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3394 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 return;
3396 }
3397
3398 uint32_t policyFlags = args->policyFlags;
3399 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003400
3401 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003402 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003403 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3404 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
3408 bool needWake;
3409 { // acquire lock
3410 mLock.lock();
3411
3412 if (shouldSendMotionToInputFilterLocked(args)) {
3413 mLock.unlock();
3414
3415 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003416 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003417 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3418 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003419 args->metaState, args->buttonState, args->classification, transform,
3420 args->xPrecision, args->yPrecision, args->xCursorPosition,
3421 args->yCursorPosition, args->downTime, args->eventTime,
3422 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
3424 policyFlags |= POLICY_FLAG_FILTERED;
3425 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3426 return; // event was consumed by the filter
3427 }
3428
3429 mLock.lock();
3430 }
3431
3432 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003433 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003434 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003435 args->displayId, policyFlags, args->action, args->actionButton,
3436 args->flags, args->metaState, args->buttonState,
3437 args->classification, args->edgeFlags, args->xPrecision,
3438 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3439 args->downTime, args->pointerCount, args->pointerProperties,
3440 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441
3442 needWake = enqueueInboundEventLocked(newEntry);
3443 mLock.unlock();
3444 } // release lock
3445
3446 if (needWake) {
3447 mLooper->wake();
3448 }
3449}
3450
3451bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003452 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453}
3454
3455void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3456#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003457 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 "switchMask=0x%08x",
3459 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460#endif
3461
3462 uint32_t policyFlags = args->policyFlags;
3463 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465}
3466
3467void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3468#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3470 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471#endif
3472
3473 bool needWake;
3474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003475 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
Prabir Pradhan42611e02018-11-27 14:04:02 -08003477 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003478 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 needWake = enqueueInboundEventLocked(newEntry);
3480 } // release lock
3481
3482 if (needWake) {
3483 mLooper->wake();
3484 }
3485}
3486
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003487InputEventInjectionResult InputDispatcher::injectInputEvent(
3488 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3489 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490#if DEBUG_INBOUND_EVENT_DETAILS
3491 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003492 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3493 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003495 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 policyFlags |= POLICY_FLAG_INJECTED;
3498 if (hasInjectionPermission(injectorPid, injectorUid)) {
3499 policyFlags |= POLICY_FLAG_TRUSTED;
3500 }
3501
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003502 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003505 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3506 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003508 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003511 int32_t flags = incomingKey.getFlags();
3512 int32_t keyCode = incomingKey.getKeyCode();
3513 int32_t metaState = incomingKey.getMetaState();
3514 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003516 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003517 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003518 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3519 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3520 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3523 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003524 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525
3526 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3527 android::base::Timer t;
3528 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3529 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3530 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3531 std::to_string(t.duration().count()).c_str());
3532 }
3533 }
3534
3535 mLock.lock();
3536 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003537 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3538 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003539 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3540 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003541 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003542 injectedEntries.push(injectedEntry);
3543 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003546 case AINPUT_EVENT_TYPE_MOTION: {
3547 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3548 int32_t action = motionEvent->getAction();
3549 size_t pointerCount = motionEvent->getPointerCount();
3550 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3551 int32_t actionButton = motionEvent->getActionButton();
3552 int32_t displayId = motionEvent->getDisplayId();
3553 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003554 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555 }
3556
3557 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3558 nsecs_t eventTime = motionEvent->getEventTime();
3559 android::base::Timer t;
3560 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3561 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3562 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3563 std::to_string(t.duration().count()).c_str());
3564 }
3565 }
3566
3567 mLock.lock();
3568 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3569 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3570 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003571 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3572 motionEvent->getSource(), motionEvent->getDisplayId(),
3573 policyFlags, action, actionButton, motionEvent->getFlags(),
3574 motionEvent->getMetaState(), motionEvent->getButtonState(),
3575 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3576 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003577 motionEvent->getRawXCursorPosition(),
3578 motionEvent->getRawYCursorPosition(),
3579 motionEvent->getDownTime(), uint32_t(pointerCount),
3580 pointerProperties, samplePointerCoords,
3581 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 injectedEntries.push(injectedEntry);
3583 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3584 sampleEventTimes += 1;
3585 samplePointerCoords += pointerCount;
3586 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003587 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003588 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 motionEvent->getDisplayId(), policyFlags, action,
3590 actionButton, motionEvent->getFlags(),
3591 motionEvent->getMetaState(), motionEvent->getButtonState(),
3592 motionEvent->getClassification(),
3593 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3594 motionEvent->getYPrecision(),
3595 motionEvent->getRawXCursorPosition(),
3596 motionEvent->getRawYCursorPosition(),
3597 motionEvent->getDownTime(), uint32_t(pointerCount),
3598 pointerProperties, samplePointerCoords,
3599 motionEvent->getXOffset(), motionEvent->getYOffset());
3600 injectedEntries.push(nextInjectedEntry);
3601 }
3602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003606 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003607 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
3610 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003611 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 injectionState->injectionIsAsync = true;
3613 }
3614
3615 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003616 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617
3618 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003619 while (!injectedEntries.empty()) {
3620 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3621 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
3624 mLock.unlock();
3625
3626 if (needWake) {
3627 mLooper->wake();
3628 }
3629
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003630 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003632 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003634 if (syncMode == InputEventInjectionSync::NONE) {
3635 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 } else {
3637 for (;;) {
3638 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003639 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 break;
3641 }
3642
3643 nsecs_t remainingTimeout = endTime - now();
3644 if (remainingTimeout <= 0) {
3645#if DEBUG_INJECTION
3646 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003649 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 break;
3651 }
3652
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003653 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
3655
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003656 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3657 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 while (injectionState->pendingForegroundDispatches != 0) {
3659#if DEBUG_INJECTION
3660 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662#endif
3663 nsecs_t remainingTimeout = endTime - now();
3664 if (remainingTimeout <= 0) {
3665#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3667 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003669 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 break;
3671 }
3672
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003673 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675 }
3676 }
3677
3678 injectionState->release();
3679 } // release lock
3680
3681#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003682 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003683 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684#endif
3685
3686 return injectionResult;
3687}
3688
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003689std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003690 std::array<uint8_t, 32> calculatedHmac;
3691 std::unique_ptr<VerifiedInputEvent> result;
3692 switch (event.getType()) {
3693 case AINPUT_EVENT_TYPE_KEY: {
3694 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3695 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3696 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003697 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003698 break;
3699 }
3700 case AINPUT_EVENT_TYPE_MOTION: {
3701 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3702 VerifiedMotionEvent verifiedMotionEvent =
3703 verifiedMotionEventFromMotionEvent(motionEvent);
3704 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003705 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003706 break;
3707 }
3708 default: {
3709 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3710 return nullptr;
3711 }
3712 }
3713 if (calculatedHmac == INVALID_HMAC) {
3714 return nullptr;
3715 }
3716 if (calculatedHmac != event.getHmac()) {
3717 return nullptr;
3718 }
3719 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003720}
3721
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 return injectorUid == 0 ||
3724 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725}
3726
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003727void InputDispatcher::setInjectionResult(EventEntry* entry,
3728 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 InjectionState* injectionState = entry->injectionState;
3730 if (injectionState) {
3731#if DEBUG_INJECTION
3732 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 "injectorPid=%d, injectorUid=%d",
3734 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735#endif
3736
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003737 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 // Log the outcome since the injector did not wait for the injection result.
3739 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003740 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 ALOGV("Asynchronous input event injection succeeded.");
3742 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003743 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003744 ALOGW("Asynchronous input event injection failed.");
3745 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 ALOGW("Asynchronous input event injection permission denied.");
3748 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003749 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003750 ALOGW("Asynchronous input event injection timed out.");
3751 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003752 case InputEventInjectionResult::PENDING:
3753 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3754 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756 }
3757
3758 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003759 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761}
3762
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003763void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 InjectionState* injectionState = entry->injectionState;
3765 if (injectionState) {
3766 injectionState->pendingForegroundDispatches += 1;
3767 }
3768}
3769
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003770void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 InjectionState* injectionState = entry->injectionState;
3772 if (injectionState) {
3773 injectionState->pendingForegroundDispatches -= 1;
3774
3775 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003776 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 }
3778 }
3779}
3780
Vishnu Nairad321cd2020-08-20 16:40:21 -07003781const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003782 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003783 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3784 auto it = mWindowHandlesByDisplay.find(displayId);
3785 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003786}
3787
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003789 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003790 if (windowHandleToken == nullptr) {
3791 return nullptr;
3792 }
3793
Arthur Hungb92218b2018-08-14 12:00:21 +08003794 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003795 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003796 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003797 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003798 return windowHandle;
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
3801 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003802 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803}
3804
Vishnu Nairad321cd2020-08-20 16:40:21 -07003805sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3806 int displayId) const {
3807 if (windowHandleToken == nullptr) {
3808 return nullptr;
3809 }
3810
3811 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3812 if (windowHandle->getToken() == windowHandleToken) {
3813 return windowHandle;
3814 }
3815 }
3816 return nullptr;
3817}
3818
3819sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3820 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3821 return getWindowHandleLocked(focusedToken, displayId);
3822}
3823
Mady Mellor017bcd12020-06-23 19:12:00 +00003824bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3825 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003826 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003827 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003828 if (handle->getId() == windowHandle->getId() &&
3829 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003830 if (windowHandle->getInfo()->displayId != it.first) {
3831 ALOGE("Found window %s in display %" PRId32
3832 ", but it should belong to display %" PRId32,
3833 windowHandle->getName().c_str(), it.first,
3834 windowHandle->getInfo()->displayId);
3835 }
3836 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839 }
3840 return false;
3841}
3842
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003843bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3844 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3845 const bool noInputChannel =
3846 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3847 if (connection != nullptr && noInputChannel) {
3848 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3849 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3850 return false;
3851 }
3852
3853 if (connection == nullptr) {
3854 if (!noInputChannel) {
3855 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3856 }
3857 return false;
3858 }
3859 if (!connection->responsive) {
3860 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3861 return false;
3862 }
3863 return true;
3864}
3865
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003866std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3867 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003868 size_t count = mInputChannelsByToken.count(token);
3869 if (count == 0) {
3870 return nullptr;
3871 }
3872 return mInputChannelsByToken.at(token);
3873}
3874
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003875void InputDispatcher::updateWindowHandlesForDisplayLocked(
3876 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3877 if (inputWindowHandles.empty()) {
3878 // Remove all handles on a display if there are no windows left.
3879 mWindowHandlesByDisplay.erase(displayId);
3880 return;
3881 }
3882
3883 // Since we compare the pointer of input window handles across window updates, we need
3884 // to make sure the handle object for the same window stays unchanged across updates.
3885 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003886 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003887 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003888 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003889 }
3890
3891 std::vector<sp<InputWindowHandle>> newHandles;
3892 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3893 if (!handle->updateInfo()) {
3894 // handle no longer valid
3895 continue;
3896 }
3897
3898 const InputWindowInfo* info = handle->getInfo();
3899 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3900 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3901 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003902 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3903 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3904 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003905 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003906 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003907 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003908 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003909 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003910 }
3911
3912 if (info->displayId != displayId) {
3913 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3914 handle->getName().c_str(), displayId, info->displayId);
3915 continue;
3916 }
3917
Robert Carredd13602020-04-13 17:24:34 -07003918 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3919 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003920 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003921 oldHandle->updateFrom(handle);
3922 newHandles.push_back(oldHandle);
3923 } else {
3924 newHandles.push_back(handle);
3925 }
3926 }
3927
3928 // Insert or replace
3929 mWindowHandlesByDisplay[displayId] = newHandles;
3930}
3931
Arthur Hung72d8dc32020-03-28 00:48:39 +00003932void InputDispatcher::setInputWindows(
3933 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3934 { // acquire lock
3935 std::scoped_lock _l(mLock);
3936 for (auto const& i : handlesPerDisplay) {
3937 setInputWindowsLocked(i.second, i.first);
3938 }
3939 }
3940 // Wake up poll loop since it may need to make new input dispatching choices.
3941 mLooper->wake();
3942}
3943
Arthur Hungb92218b2018-08-14 12:00:21 +08003944/**
3945 * Called from InputManagerService, update window handle list by displayId that can receive input.
3946 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3947 * If set an empty list, remove all handles from the specific display.
3948 * For focused handle, check if need to change and send a cancel event to previous one.
3949 * For removed handle, check if need to send a cancel event if already in touch.
3950 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003951void InputDispatcher::setInputWindowsLocked(
3952 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003953 if (DEBUG_FOCUS) {
3954 std::string windowList;
3955 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3956 windowList += iwh->getName() + " ";
3957 }
3958 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003961 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3962 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3963 const bool noInputWindow =
3964 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3965 if (noInputWindow && window->getToken() != nullptr) {
3966 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3967 window->getName().c_str());
3968 window->releaseChannel();
3969 }
3970 }
3971
Arthur Hung72d8dc32020-03-28 00:48:39 +00003972 // Copy old handles for release if they are no longer present.
3973 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Arthur Hung72d8dc32020-03-28 00:48:39 +00003975 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003976
Vishnu Nair958da932020-08-21 17:12:37 -07003977 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3978 if (mLastHoverWindowHandle &&
3979 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
3980 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003981 mLastHoverWindowHandle = nullptr;
3982 }
3983
Vishnu Nair958da932020-08-21 17:12:37 -07003984 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3985 if (focusedToken) {
3986 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
3987 if (result != FocusResult::OK) {
3988 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
3989 }
3990 }
3991
3992 std::optional<FocusRequest> focusRequest =
3993 getOptionalValueByKey(mPendingFocusRequests, displayId);
3994 if (focusRequest) {
3995 // If the window from the pending request is now visible, provide it focus.
3996 FocusResult result = handleFocusRequestLocked(*focusRequest);
3997 if (result != FocusResult::NOT_VISIBLE) {
3998 // Drop the request if we were able to change the focus or we cannot change
3999 // it for another reason.
4000 mPendingFocusRequests.erase(displayId);
4001 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004004 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4005 mTouchStatesByDisplay.find(displayId);
4006 if (stateIt != mTouchStatesByDisplay.end()) {
4007 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004008 for (size_t i = 0; i < state.windows.size();) {
4009 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004010 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004012 ALOGD("Touched window was removed: %s in display %" PRId32,
4013 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004014 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004015 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004016 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4017 if (touchedInputChannel != nullptr) {
4018 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4019 "touched window was removed");
4020 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004022 state.windows.erase(state.windows.begin() + i);
4023 } else {
4024 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
4026 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004027 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004028
Arthur Hung72d8dc32020-03-28 00:48:39 +00004029 // Release information for windows that are no longer present.
4030 // This ensures that unused input channels are released promptly.
4031 // Otherwise, they might stick around until the window handle is destroyed
4032 // which might not happen until the next GC.
4033 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004034 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004035 if (DEBUG_FOCUS) {
4036 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004037 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004038 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004039 }
chaviw291d88a2019-02-14 10:33:58 -08004040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041}
4042
4043void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004044 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004045 if (DEBUG_FOCUS) {
4046 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4047 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4048 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004049 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004050 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Chris Yea209fde2020-07-22 13:54:51 -07004052 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004053 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004054
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004055 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4056 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004057 }
4058
Chris Yea209fde2020-07-22 13:54:51 -07004059 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004060 if (inputApplicationHandle != nullptr) {
4061 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4062 } else {
4063 mFocusedApplicationHandlesByDisplay.erase(displayId);
4064 }
4065
4066 // No matter what the old focused application was, stop waiting on it because it is
4067 // no longer focused.
4068 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 } // release lock
4070
4071 // Wake up poll loop since it may need to make new input dispatching choices.
4072 mLooper->wake();
4073}
4074
Tiger Huang721e26f2018-07-24 22:26:19 +08004075/**
4076 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4077 * the display not specified.
4078 *
4079 * We track any unreleased events for each window. If a window loses the ability to receive the
4080 * released event, we will send a cancel event to it. So when the focused display is changed, we
4081 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4082 * display. The display-specified events won't be affected.
4083 */
4084void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004085 if (DEBUG_FOCUS) {
4086 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4087 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004088 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004089 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004090
4091 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004092 sp<IBinder> oldFocusedWindowToken =
4093 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4094 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004095 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004096 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004097 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 CancelationOptions
4099 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4100 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004101 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004102 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4103 }
4104 }
4105 mFocusedDisplayId = displayId;
4106
Chris Ye3c2d6f52020-08-09 10:39:48 -07004107 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004108 sp<IBinder> newFocusedWindowToken =
4109 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4110 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004111
Vishnu Nairad321cd2020-08-20 16:40:21 -07004112 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004113 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004114 if (!mFocusedWindowTokenByDisplay.empty()) {
4115 ALOGE("But another display has a focused window\n%s",
4116 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004117 }
4118 }
4119 }
4120
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004121 if (DEBUG_FOCUS) {
4122 logDispatchStateLocked();
4123 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004124 } // release lock
4125
4126 // Wake up poll loop since it may need to make new input dispatching choices.
4127 mLooper->wake();
4128}
4129
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004131 if (DEBUG_FOCUS) {
4132 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
4135 bool changed;
4136 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004137 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
4139 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4140 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004141 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143
4144 if (mDispatchEnabled && !enabled) {
4145 resetAndDropEverythingLocked("dispatcher is being disabled");
4146 }
4147
4148 mDispatchEnabled = enabled;
4149 mDispatchFrozen = frozen;
4150 changed = true;
4151 } else {
4152 changed = false;
4153 }
4154
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004155 if (DEBUG_FOCUS) {
4156 logDispatchStateLocked();
4157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 } // release lock
4159
4160 if (changed) {
4161 // Wake up poll loop since it may need to make new input dispatching choices.
4162 mLooper->wake();
4163 }
4164}
4165
4166void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004167 if (DEBUG_FOCUS) {
4168 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170
4171 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004172 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
4174 if (mInputFilterEnabled == enabled) {
4175 return;
4176 }
4177
4178 mInputFilterEnabled = enabled;
4179 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4180 } // release lock
4181
4182 // Wake up poll loop since there might be work to do to drop everything.
4183 mLooper->wake();
4184}
4185
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004186void InputDispatcher::setInTouchMode(bool inTouchMode) {
4187 std::scoped_lock lock(mLock);
4188 mInTouchMode = inTouchMode;
4189}
4190
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004191void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4192 if (opacity < 0 || opacity > 1) {
4193 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4194 return;
4195 }
4196
4197 std::scoped_lock lock(mLock);
4198 mMaximumObscuringOpacityForTouch = opacity;
4199}
4200
4201void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4202 std::scoped_lock lock(mLock);
4203 mBlockUntrustedTouchesMode = mode;
4204}
4205
chaviwfbe5d9c2018-12-26 12:23:37 -08004206bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4207 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004208 if (DEBUG_FOCUS) {
4209 ALOGD("Trivial transfer to same window.");
4210 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004211 return true;
4212 }
4213
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004215 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
chaviwfbe5d9c2018-12-26 12:23:37 -08004217 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4218 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004219 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004220 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 return false;
4222 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004223 if (DEBUG_FOCUS) {
4224 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4225 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004228 if (DEBUG_FOCUS) {
4229 ALOGD("Cannot transfer focus because windows are on different displays.");
4230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 return false;
4232 }
4233
4234 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004235 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4236 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004237 for (size_t i = 0; i < state.windows.size(); i++) {
4238 const TouchedWindow& touchedWindow = state.windows[i];
4239 if (touchedWindow.windowHandle == fromWindowHandle) {
4240 int32_t oldTargetFlags = touchedWindow.targetFlags;
4241 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004243 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 int32_t newTargetFlags = oldTargetFlags &
4246 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4247 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004248 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
Jeff Brownf086ddb2014-02-11 14:28:48 -08004250 found = true;
4251 goto Found;
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004258 if (DEBUG_FOCUS) {
4259 ALOGD("Focus transfer failed because from window did not have focus.");
4260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 return false;
4262 }
4263
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004264 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4265 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004266 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004267 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 CancelationOptions
4269 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4270 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004272 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004275 if (DEBUG_FOCUS) {
4276 logDispatchStateLocked();
4277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 } // release lock
4279
4280 // Wake up poll loop since it may need to make new input dispatching choices.
4281 mLooper->wake();
4282 return true;
4283}
4284
4285void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004286 if (DEBUG_FOCUS) {
4287 ALOGD("Resetting and dropping all events (%s).", reason);
4288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289
4290 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4291 synthesizeCancelationEventsForAllConnectionsLocked(options);
4292
4293 resetKeyRepeatLocked();
4294 releasePendingEventLocked();
4295 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004296 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004298 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004299 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004301 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302}
4303
4304void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004305 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 dumpDispatchStateLocked(dump);
4307
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004308 std::istringstream stream(dump);
4309 std::string line;
4310
4311 while (std::getline(stream, line, '\n')) {
4312 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314}
4315
Vishnu Nairad321cd2020-08-20 16:40:21 -07004316std::string InputDispatcher::dumpFocusedWindowsLocked() {
4317 if (mFocusedWindowTokenByDisplay.empty()) {
4318 return INDENT "FocusedWindows: <none>\n";
4319 }
4320
4321 std::string dump;
4322 dump += INDENT "FocusedWindows:\n";
4323 for (auto& it : mFocusedWindowTokenByDisplay) {
4324 const int32_t displayId = it.first;
4325 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4326 if (windowHandle) {
4327 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4328 windowHandle->getName().c_str());
4329 } else {
4330 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4331 " has focused token without a window'\n",
4332 displayId);
4333 }
4334 }
4335 return dump;
4336}
4337
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004339 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4340 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4341 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004342 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Tiger Huang721e26f2018-07-24 22:26:19 +08004344 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4345 dump += StringPrintf(INDENT "FocusedApplications:\n");
4346 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4347 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004348 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004349 const std::chrono::duration timeout =
4350 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004352 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004353 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004356 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004358
Vishnu Nairad321cd2020-08-20 16:40:21 -07004359 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004361 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004362 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004363 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4364 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004365 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 state.displayId, toString(state.down), toString(state.split),
4367 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004368 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004370 for (size_t i = 0; i < state.windows.size(); i++) {
4371 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004372 dump += StringPrintf(INDENT4
4373 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4374 i, touchedWindow.windowHandle->getName().c_str(),
4375 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004376 }
4377 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004378 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004379 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004380 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004381 dump += INDENT3 "Portal windows:\n";
4382 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004383 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004384 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4385 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004386 }
4387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392
Arthur Hungb92218b2018-08-14 12:00:21 +08004393 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004395 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004396 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004397 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004398 dump += INDENT2 "Windows:\n";
4399 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004400 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004401 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402
Arthur Hungb92218b2018-08-14 12:00:21 +08004403 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004404 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4405 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004406 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004408 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004409 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 i, windowInfo->name.c_str(), windowInfo->displayId,
4411 windowInfo->portalToDisplayId,
4412 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004413 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 toString(windowInfo->hasWallpaper),
4415 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004416 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004417 static_cast<int32_t>(windowInfo->type),
4418 windowInfo->frameLeft, windowInfo->frameTop,
4419 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004420 windowInfo->globalScaleFactor,
4421 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004422 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004423 dump += StringPrintf(", inputFeatures=%s",
4424 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004425 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4426 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004427 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004428 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004429 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004430 }
4431 } else {
4432 dump += INDENT2 "Windows: <none>\n";
4433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
4435 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004436 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 }
4438
Michael Wright3dd60e22019-03-27 22:06:44 +00004439 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004441 const std::vector<Monitor>& monitors = it.second;
4442 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4443 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 }
4445 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 const std::vector<Monitor>& monitors = it.second;
4447 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4448 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004451 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
4453
4454 nsecs_t currentTime = now();
4455
4456 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004457 if (!mRecentQueue.empty()) {
4458 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4459 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004460 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004462 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 }
4464 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004465 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467
4468 // Dump event currently being dispatched.
4469 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004470 dump += INDENT "PendingEvent:\n";
4471 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004473 dump += StringPrintf(", age=%" PRId64 "ms\n",
4474 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004476 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 }
4478
4479 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004480 if (!mInboundQueue.empty()) {
4481 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4482 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004483 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004485 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 }
4487 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004488 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 }
4490
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004491 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004492 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004493 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4494 const KeyReplacement& replacement = pair.first;
4495 int32_t newKeyCode = pair.second;
4496 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004497 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004498 }
4499 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004500 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004501 }
4502
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004503 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004504 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004505 for (const auto& pair : mConnectionsByFd) {
4506 const sp<Connection>& connection = pair.second;
4507 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004508 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004509 pair.first, connection->getInputChannelName().c_str(),
4510 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004511 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004513 if (!connection->outboundQueue.empty()) {
4514 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4515 connection->outboundQueue.size());
4516 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 dump.append(INDENT4);
4518 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004519 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4520 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004521 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004522 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004525 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 }
4527
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004528 if (!connection->waitQueue.empty()) {
4529 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4530 connection->waitQueue.size());
4531 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004532 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004534 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004535 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004536 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004537 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004538 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 }
4540 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004541 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 }
4543 }
4544 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004545 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547
4548 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004549 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4550 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004552 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 }
4554
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004555 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004556 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4557 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4558 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559}
4560
Michael Wright3dd60e22019-03-27 22:06:44 +00004561void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4562 const size_t numMonitors = monitors.size();
4563 for (size_t i = 0; i < numMonitors; i++) {
4564 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004565 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004566 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4567 dump += "\n";
4568 }
4569}
4570
Garfield Tan15601662020-09-22 15:32:38 -07004571base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4572 const std::string& name) {
4573#if DEBUG_CHANNEL_CREATION
4574 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575#endif
4576
Garfield Tan15601662020-09-22 15:32:38 -07004577 std::shared_ptr<InputChannel> serverChannel;
4578 std::unique_ptr<InputChannel> clientChannel;
4579 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4580
4581 if (result) {
4582 return base::Error(result) << "Failed to open input channel pair with name " << name;
4583 }
4584
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004586 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004587 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
Garfield Tan15601662020-09-22 15:32:38 -07004589 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004590 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004591 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4594 } // release lock
4595
4596 // Wake the looper because some connections have changed.
4597 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004598 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599}
4600
Garfield Tan15601662020-09-22 15:32:38 -07004601base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4602 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4603 std::shared_ptr<InputChannel> serverChannel;
4604 std::unique_ptr<InputChannel> clientChannel;
4605 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4606 if (result) {
4607 return base::Error(result) << "Failed to open input channel pair with name " << name;
4608 }
4609
Michael Wright3dd60e22019-03-27 22:06:44 +00004610 { // acquire lock
4611 std::scoped_lock _l(mLock);
4612
4613 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004614 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4615 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004616 }
4617
Garfield Tan15601662020-09-22 15:32:38 -07004618 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004619
Garfield Tan15601662020-09-22 15:32:38 -07004620 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004621 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004622 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004623
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004624 auto& monitorsByDisplay =
4625 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004626 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004627
4628 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004629 }
Garfield Tan15601662020-09-22 15:32:38 -07004630
Michael Wright3dd60e22019-03-27 22:06:44 +00004631 // Wake the looper because some connections have changed.
4632 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004633 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004634}
4635
Garfield Tan15601662020-09-22 15:32:38 -07004636status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004638 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
Garfield Tan15601662020-09-22 15:32:38 -07004640 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 if (status) {
4642 return status;
4643 }
4644 } // release lock
4645
4646 // Wake the poll loop because removing the connection may have changed the current
4647 // synchronization state.
4648 mLooper->wake();
4649 return OK;
4650}
4651
Garfield Tan15601662020-09-22 15:32:38 -07004652status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4653 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004654 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004655 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004656 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 return BAD_VALUE;
4658 }
4659
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004660 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004661 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004662
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004664 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
4666
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004667 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668
4669 nsecs_t currentTime = now();
4670 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4671
4672 connection->status = Connection::STATUS_ZOMBIE;
4673 return OK;
4674}
4675
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004676void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4677 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4678 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004679}
4680
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004681void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004682 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004683 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004684 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004685 std::vector<Monitor>& monitors = it->second;
4686 const size_t numMonitors = monitors.size();
4687 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004688 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004689 monitors.erase(monitors.begin() + i);
4690 break;
4691 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004692 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004693 if (monitors.empty()) {
4694 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004695 } else {
4696 ++it;
4697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 }
4699}
4700
Michael Wright3dd60e22019-03-27 22:06:44 +00004701status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4702 { // acquire lock
4703 std::scoped_lock _l(mLock);
4704 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4705
4706 if (!foundDisplayId) {
4707 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4708 return BAD_VALUE;
4709 }
4710 int32_t displayId = foundDisplayId.value();
4711
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004712 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4713 mTouchStatesByDisplay.find(displayId);
4714 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004715 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4716 return BAD_VALUE;
4717 }
4718
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004719 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004720 std::optional<int32_t> foundDeviceId;
4721 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004722 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004723 foundDeviceId = state.deviceId;
4724 }
4725 }
4726 if (!foundDeviceId || !state.down) {
4727 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004729 return BAD_VALUE;
4730 }
4731 int32_t deviceId = foundDeviceId.value();
4732
4733 // Send cancel events to all the input channels we're stealing from.
4734 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004736 options.deviceId = deviceId;
4737 options.displayId = displayId;
4738 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004739 std::shared_ptr<InputChannel> channel =
4740 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004741 if (channel != nullptr) {
4742 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4743 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004744 }
4745 // Then clear the current touch state so we stop dispatching to them as well.
4746 state.filterNonMonitors();
4747 }
4748 return OK;
4749}
4750
Michael Wright3dd60e22019-03-27 22:06:44 +00004751std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4752 const sp<IBinder>& token) {
4753 for (const auto& it : mGestureMonitorsByDisplay) {
4754 const std::vector<Monitor>& monitors = it.second;
4755 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004756 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004757 return it.first;
4758 }
4759 }
4760 }
4761 return std::nullopt;
4762}
4763
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004764sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004765 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004766 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004767 }
4768
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004769 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004770 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004771 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004772 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 }
4774 }
Robert Carr4e670e52018-08-15 13:26:12 -07004775
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004776 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777}
4778
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004779void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004781 removeByValue(mConnectionsByFd, connection);
4782}
4783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4785 const sp<Connection>& connection, uint32_t seq,
4786 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004787 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4788 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 commandEntry->connection = connection;
4790 commandEntry->eventTime = currentTime;
4791 commandEntry->seq = seq;
4792 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004793 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794}
4795
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4797 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004801 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4802 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004804 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805}
4806
Vishnu Nairad321cd2020-08-20 16:40:21 -07004807void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4808 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004809 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4810 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004811 commandEntry->oldToken = oldToken;
4812 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004813 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004814}
4815
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004816void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4818 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004819 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004821 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822 return;
4823 }
4824 /**
4825 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4826 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4827 * has changed. This could cause newer entries to time out before the already dispatched
4828 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4829 * processes the events linearly. So providing information about the oldest entry seems to be
4830 * most useful.
4831 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004832 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4834 std::string reason =
4835 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004836 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 ns2ms(currentWait),
4838 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004840 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 reason);
4842
4843 std::unique_ptr<CommandEntry> commandEntry =
4844 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4845 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004846 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847 commandEntry->reason = std::move(reason);
4848 postCommandLocked(std::move(commandEntry));
4849}
4850
Chris Yea209fde2020-07-22 13:54:51 -07004851void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4853 application->getName().c_str());
4854
4855 updateLastAnrStateLocked(application, reason);
4856
4857 std::unique_ptr<CommandEntry> commandEntry =
4858 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4859 commandEntry->inputApplicationHandle = application;
4860 commandEntry->inputChannel = nullptr;
4861 commandEntry->reason = std::move(reason);
4862 postCommandLocked(std::move(commandEntry));
4863}
4864
4865void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4866 const std::string& reason) {
4867 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4868 updateLastAnrStateLocked(windowLabel, reason);
4869}
4870
Chris Yea209fde2020-07-22 13:54:51 -07004871void InputDispatcher::updateLastAnrStateLocked(
4872 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4874 updateLastAnrStateLocked(windowLabel, reason);
4875}
4876
4877void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4878 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004880 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 struct tm tm;
4882 localtime_r(&t, &tm);
4883 char timestr[64];
4884 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004885 mLastAnrState.clear();
4886 mLastAnrState += INDENT "ANR:\n";
4887 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4889 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004890 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891}
4892
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004893void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 mLock.unlock();
4895
4896 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4897
4898 mLock.lock();
4899}
4900
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004901void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 sp<Connection> connection = commandEntry->connection;
4903
4904 if (connection->status != Connection::STATUS_ZOMBIE) {
4905 mLock.unlock();
4906
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004907 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
4909 mLock.lock();
4910 }
4911}
4912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004914 sp<IBinder> oldToken = commandEntry->oldToken;
4915 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004916 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004917 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004918 mLock.lock();
4919}
4920
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004921void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004922 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004923 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 mLock.unlock();
4925
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004926 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004927 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928
4929 mLock.lock();
4930
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004931 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004932 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4933 } else {
4934 // stop waking up for events in this connection, it is already not responding
4935 sp<Connection> connection = getConnectionLocked(token);
4936 if (connection == nullptr) {
4937 return;
4938 }
4939 cancelEventsForAnrLocked(connection);
4940 }
4941}
4942
Chris Yea209fde2020-07-22 13:54:51 -07004943void InputDispatcher::extendAnrTimeoutsLocked(
4944 const std::shared_ptr<InputApplicationHandle>& application,
4945 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004946 if (connectionToken == nullptr && application != nullptr) {
4947 // The ANR happened because there's no focused window
4948 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4949 mAwaitedFocusedApplication = application;
4950 }
4951
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004952 sp<Connection> connection = getConnectionLocked(connectionToken);
4953 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004954 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004955 return;
4956 }
4957
4958 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004959 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960
4961 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004962 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 for (DispatchEntry* entry : connection->waitQueue) {
4964 if (newTimeout >= entry->timeoutTime) {
4965 // Already removed old entries when connection was marked unresponsive
4966 entry->timeoutTime = newTimeout;
4967 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4968 }
4969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970}
4971
4972void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4973 CommandEntry* commandEntry) {
4974 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004975 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
4977 mLock.unlock();
4978
Michael Wright2b3c3302018-03-02 17:19:13 +00004979 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004981 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004982 : nullptr;
4983 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004984 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4985 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004986 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988
4989 mLock.lock();
4990
4991 if (delay < 0) {
4992 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4993 } else if (!delay) {
4994 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4995 } else {
4996 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4997 entry->interceptKeyWakeupTime = now() + delay;
4998 }
4999 entry->release();
5000}
5001
chaviwfd6d3512019-03-25 13:23:49 -07005002void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5003 mLock.unlock();
5004 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5005 mLock.lock();
5006}
5007
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005008/**
5009 * Connection is responsive if it has no events in the waitQueue that are older than the
5010 * current time.
5011 */
5012static bool isConnectionResponsive(const Connection& connection) {
5013 const nsecs_t currentTime = now();
5014 for (const DispatchEntry* entry : connection.waitQueue) {
5015 if (entry->timeoutTime < currentTime) {
5016 return false;
5017 }
5018 }
5019 return true;
5020}
5021
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005024 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005026 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027
5028 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005029 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005030 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005031 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005033 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005034 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005035 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005036 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5037 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005038 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005039 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005040
5041 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005042 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005043 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5044 restartEvent =
5045 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005046 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005047 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5048 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5049 handled);
5050 } else {
5051 restartEvent = false;
5052 }
5053
5054 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005055 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005056 // contents of the wait queue to have been drained, so we need to double-check
5057 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005058 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5059 if (dispatchEntryIt != connection->waitQueue.end()) {
5060 dispatchEntry = *dispatchEntryIt;
5061 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005062 mAnrTracker.erase(dispatchEntry->timeoutTime,
5063 connection->inputChannel->getConnectionToken());
5064 if (!connection->responsive) {
5065 connection->responsive = isConnectionResponsive(*connection);
5066 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005067 traceWaitQueueLength(connection);
5068 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005069 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005070 traceOutboundQueueLength(connection);
5071 } else {
5072 releaseDispatchEntry(dispatchEntry);
5073 }
5074 }
5075
5076 // Start the next dispatch cycle for this connection.
5077 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078}
5079
5080bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005081 DispatchEntry* dispatchEntry,
5082 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005083 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005084 if (!handled) {
5085 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005086 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005088 return false;
5089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005091 // Get the fallback key state.
5092 // Clear it out after dispatching the UP.
5093 int32_t originalKeyCode = keyEntry->keyCode;
5094 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5095 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5096 connection->inputState.removeFallbackKey(originalKeyCode);
5097 }
5098
5099 if (handled || !dispatchEntry->hasForegroundTarget()) {
5100 // If the application handles the original key for which we previously
5101 // generated a fallback or if the window is not a foreground window,
5102 // then cancel the associated fallback key, if any.
5103 if (fallbackKeyCode != -1) {
5104 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005106 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5108 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5109 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005111 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005112 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113
5114 mLock.unlock();
5115
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005116 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005117 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118
5119 mLock.lock();
5120
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005121 // Cancel the fallback key.
5122 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005124 "application handled the original non-fallback key "
5125 "or is no longer a foreground target, "
5126 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 options.keyCode = fallbackKeyCode;
5128 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005130 connection->inputState.removeFallbackKey(originalKeyCode);
5131 }
5132 } else {
5133 // If the application did not handle a non-fallback key, first check
5134 // that we are in a good state to perform unhandled key event processing
5135 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005136 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005137 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005139 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005140 "since this is not an initial down. "
5141 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5142 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005144 return false;
5145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005147 // Dispatch the unhandled key to the policy.
5148#if DEBUG_OUTBOUND_EVENT_DETAILS
5149 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005150 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5151 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005152#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005153 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005154
5155 mLock.unlock();
5156
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005157 bool fallback =
5158 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5159 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005160
5161 mLock.lock();
5162
5163 if (connection->status != Connection::STATUS_NORMAL) {
5164 connection->inputState.removeFallbackKey(originalKeyCode);
5165 return false;
5166 }
5167
5168 // Latch the fallback keycode for this key on an initial down.
5169 // The fallback keycode cannot change at any other point in the lifecycle.
5170 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005172 fallbackKeyCode = event.getKeyCode();
5173 } else {
5174 fallbackKeyCode = AKEYCODE_UNKNOWN;
5175 }
5176 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5177 }
5178
5179 ALOG_ASSERT(fallbackKeyCode != -1);
5180
5181 // Cancel the fallback key if the policy decides not to send it anymore.
5182 // We will continue to dispatch the key to the policy but we will no
5183 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005184 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5185 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005186#if DEBUG_OUTBOUND_EVENT_DETAILS
5187 if (fallback) {
5188 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005189 "as a fallback for %d, but on the DOWN it had requested "
5190 "to send %d instead. Fallback canceled.",
5191 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005192 } else {
5193 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005194 "but on the DOWN it had requested to send %d. "
5195 "Fallback canceled.",
5196 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005197 }
5198#endif
5199
5200 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5201 "canceling fallback, policy no longer desires it");
5202 options.keyCode = fallbackKeyCode;
5203 synthesizeCancelationEventsForConnectionLocked(connection, options);
5204
5205 fallback = false;
5206 fallbackKeyCode = AKEYCODE_UNKNOWN;
5207 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005209 }
5210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211
5212#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005213 {
5214 std::string msg;
5215 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5216 connection->inputState.getFallbackKeys();
5217 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005218 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005220 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005221 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005222 }
5223#endif
5224
5225 if (fallback) {
5226 // Restart the dispatch cycle using the fallback key.
5227 keyEntry->eventTime = event.getEventTime();
5228 keyEntry->deviceId = event.getDeviceId();
5229 keyEntry->source = event.getSource();
5230 keyEntry->displayId = event.getDisplayId();
5231 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5232 keyEntry->keyCode = fallbackKeyCode;
5233 keyEntry->scanCode = event.getScanCode();
5234 keyEntry->metaState = event.getMetaState();
5235 keyEntry->repeatCount = event.getRepeatCount();
5236 keyEntry->downTime = event.getDownTime();
5237 keyEntry->syntheticRepeat = false;
5238
5239#if DEBUG_OUTBOUND_EVENT_DETAILS
5240 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005241 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5242 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005243#endif
5244 return true; // restart the event
5245 } else {
5246#if DEBUG_OUTBOUND_EVENT_DETAILS
5247 ALOGD("Unhandled key event: No fallback key.");
5248#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005249
5250 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005251 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253 }
5254 return false;
5255}
5256
5257bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005258 DispatchEntry* dispatchEntry,
5259 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 return false;
5261}
5262
5263void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5264 mLock.unlock();
5265
5266 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5267
5268 mLock.lock();
5269}
5270
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005271KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5272 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005273 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005274 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5275 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005276 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277}
5278
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005279void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5280 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 // TODO Write some statistics about how long we spend waiting.
5282}
5283
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005284/**
5285 * Report the touch event latency to the statsd server.
5286 * Input events are reported for statistics if:
5287 * - This is a touchscreen event
5288 * - InputFilter is not enabled
5289 * - Event is not injected or synthesized
5290 *
5291 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5292 * from getting aggregated with the "old" data.
5293 */
5294void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5295 REQUIRES(mLock) {
5296 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5297 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5298 if (!reportForStatistics) {
5299 return;
5300 }
5301
5302 if (mTouchStatistics.shouldReport()) {
5303 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5304 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5305 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5306 mTouchStatistics.reset();
5307 }
5308 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5309 mTouchStatistics.addValue(latencyMicros);
5310}
5311
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312void InputDispatcher::traceInboundQueueLengthLocked() {
5313 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005314 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
5316}
5317
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005318void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 if (ATRACE_ENABLED()) {
5320 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005321 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005322 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
5324}
5325
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005326void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 if (ATRACE_ENABLED()) {
5328 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005329 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005330 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 }
5332}
5333
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005337 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 dumpDispatchStateLocked(dump);
5339
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005340 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005341 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005342 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 }
5344}
5345
5346void InputDispatcher::monitor() {
5347 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005348 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005350 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351}
5352
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005353/**
5354 * Wake up the dispatcher and wait until it processes all events and commands.
5355 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5356 * this method can be safely called from any thread, as long as you've ensured that
5357 * the work you are interested in completing has already been queued.
5358 */
5359bool InputDispatcher::waitForIdle() {
5360 /**
5361 * Timeout should represent the longest possible time that a device might spend processing
5362 * events and commands.
5363 */
5364 constexpr std::chrono::duration TIMEOUT = 100ms;
5365 std::unique_lock lock(mLock);
5366 mLooper->wake();
5367 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5368 return result == std::cv_status::no_timeout;
5369}
5370
Vishnu Naire798b472020-07-23 13:52:21 -07005371/**
5372 * Sets focus to the window identified by the token. This must be called
5373 * after updating any input window handles.
5374 *
5375 * Params:
5376 * request.token - input channel token used to identify the window that should gain focus.
5377 * request.focusedToken - the token that the caller expects currently to be focused. If the
5378 * specified token does not match the currently focused window, this request will be dropped.
5379 * If the specified focused token matches the currently focused window, the call will succeed.
5380 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5381 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5382 * when requesting the focus change. This determines which request gets
5383 * precedence if there is a focus change request from another source such as pointer down.
5384 */
Vishnu Nair958da932020-08-21 17:12:37 -07005385void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5386 { // acquire lock
5387 std::scoped_lock _l(mLock);
5388
5389 const int32_t displayId = request.displayId;
5390 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5391 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5392 ALOGD_IF(DEBUG_FOCUS,
5393 "setFocusedWindow on display %" PRId32
5394 " ignored, reason: focusedToken is not focused",
5395 displayId);
5396 return;
5397 }
5398
5399 mPendingFocusRequests.erase(displayId);
5400 FocusResult result = handleFocusRequestLocked(request);
5401 if (result == FocusResult::NOT_VISIBLE) {
5402 // The requested window is not currently visible. Wait for the window to become visible
5403 // and then provide it focus. This is to handle situations where a user action triggers
5404 // a new window to appear. We want to be able to queue any key events after the user
5405 // action and deliver it to the newly focused window. In order for this to happen, we
5406 // take focus from the currently focused window so key events can be queued.
5407 ALOGD_IF(DEBUG_FOCUS,
5408 "setFocusedWindow on display %" PRId32
5409 " pending, reason: window is not visible",
5410 displayId);
5411 mPendingFocusRequests[displayId] = request;
5412 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5413 "setFocusedWindow_AwaitingWindowVisibility");
5414 } else if (result != FocusResult::OK) {
5415 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5416 typeToString(result));
5417 }
5418 } // release lock
5419 // Wake up poll loop since it may need to make new input dispatching choices.
5420 mLooper->wake();
5421}
5422
5423InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5424 const FocusRequest& request) {
5425 const int32_t displayId = request.displayId;
5426 const sp<IBinder> newFocusedToken = request.token;
5427 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5428
5429 if (oldFocusedToken == request.token) {
5430 ALOGD_IF(DEBUG_FOCUS,
5431 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5432 displayId);
5433 return FocusResult::OK;
5434 }
5435
5436 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5437 if (result != FocusResult::OK) {
5438 return result;
5439 }
5440
5441 std::string_view reason =
5442 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5443 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5444 return FocusResult::OK;
5445}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005446
Vishnu Nairad321cd2020-08-20 16:40:21 -07005447void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5448 const sp<IBinder>& newFocusedToken, int32_t displayId,
5449 std::string_view reason) {
5450 if (oldFocusedToken) {
5451 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005452 if (focusedInputChannel) {
5453 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5454 "focus left window");
5455 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005456 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005457 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005458 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005459 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005460 if (newFocusedToken) {
5461 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5462 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005463 }
5464
5465 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005466 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005467 }
5468}
Vishnu Nair958da932020-08-21 17:12:37 -07005469
5470/**
5471 * Checks if the window token can be focused on a display. The token can be focused if there is
5472 * at least one window handle that is visible with the same token and all window handles with the
5473 * same token are focusable.
5474 *
5475 * In the case of mirroring, two windows may share the same window token and their visibility
5476 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5477 * we expect the focusability of the windows to match since its hard to reason why one window can
5478 * receive focus events and the other cannot when both are backed by the same input channel.
5479 */
5480InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5481 int32_t displayId) const {
5482 bool allWindowsAreFocusable = true;
5483 bool visibleWindowFound = false;
5484 bool windowFound = false;
5485 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5486 if (window->getToken() != token) {
5487 continue;
5488 }
5489 windowFound = true;
5490 if (window->getInfo()->visible) {
5491 // Check if at least a single window is visible.
5492 visibleWindowFound = true;
5493 }
5494 if (!window->getInfo()->focusable) {
5495 // Check if all windows with the window token are focusable.
5496 allWindowsAreFocusable = false;
5497 break;
5498 }
5499 }
5500
5501 if (!windowFound) {
5502 return FocusResult::NO_WINDOW;
5503 }
5504 if (!allWindowsAreFocusable) {
5505 return FocusResult::NOT_FOCUSABLE;
5506 }
5507 if (!visibleWindowFound) {
5508 return FocusResult::NOT_VISIBLE;
5509 }
5510
5511 return FocusResult::OK;
5512}
Garfield Tane84e6f92019-08-29 17:28:41 -07005513} // namespace android::inputdispatcher