blob: d7aea4e89153770c00208c5a85fb43c1cccee4fa [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 Vishniakou14411c92020-09-18 21:15:05 -0500223static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
224 constexpr size_t maxEntries = 50; // max events to print
225 constexpr size_t skipBegin = maxEntries / 2;
226 const size_t skipEnd = queue.size() - maxEntries / 2;
227 // skip from maxEntries / 2 ... size() - maxEntries/2
228 // only print from 0 .. skipBegin and then from skipEnd .. size()
229
230 std::string dump;
231 for (size_t i = 0; i < queue.size(); i++) {
232 const DispatchEntry& entry = *queue[i];
233 if (i >= skipBegin && i < skipEnd) {
234 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
235 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
236 continue;
237 }
238 dump.append(INDENT4);
239 dump += entry.eventEntry->getDescription();
240 dump += StringPrintf(", seq=%" PRIu32
241 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
242 entry.seq, entry.targetFlags, entry.resolvedAction,
243 ns2ms(currentTime - entry.eventEntry->eventTime));
244 if (entry.deliveryTime != 0) {
245 // This entry was delivered, so add information on how long we've been waiting
246 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
247 }
248 dump.append("\n");
249 }
250 return dump;
251}
252
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700253/**
254 * Find the entry in std::unordered_map by key, and return it.
255 * If the entry is not found, return a default constructed entry.
256 *
257 * Useful when the entries are vectors, since an empty vector will be returned
258 * if the entry is not found.
259 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
260 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700261template <typename K, typename V>
262static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700263 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700264 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800265}
266
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700267/**
268 * Find the entry in std::unordered_map by value, and remove it.
269 * If more than one entry has the same value, then all matching
270 * key-value pairs will be removed.
271 *
272 * Return true if at least one value has been removed.
273 */
274template <typename K, typename V>
275static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
276 bool removed = false;
277 for (auto it = map.begin(); it != map.end();) {
278 if (it->second == value) {
279 it = map.erase(it);
280 removed = true;
281 } else {
282 it++;
283 }
284 }
285 return removed;
286}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800287
Vishnu Nair958da932020-08-21 17:12:37 -0700288/**
289 * Find the entry in std::unordered_map by key and return the value as an optional.
290 */
291template <typename K, typename V>
292static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
293 auto it = map.find(key);
294 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
295}
296
chaviwaf87b3e2019-10-01 16:59:28 -0700297static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
298 if (first == second) {
299 return true;
300 }
301
302 if (first == nullptr || second == nullptr) {
303 return false;
304 }
305
306 return first->getToken() == second->getToken();
307}
308
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800309static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
310 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
311}
312
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000313static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
314 EventEntry* eventEntry,
315 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 if (inputTarget.useDefaultPointerTransform()) {
317 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 inputTargetFlags, transform,
320 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321 }
322
323 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
325
326 PointerCoords pointerCoords[motionEntry.pointerCount];
327
328 // Use the first pointer information to normalize all other pointers. This could be any pointer
329 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700330 // uses the transform for the normalized pointer.
331 const ui::Transform& firstPointerTransform =
332 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
333 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000334
335 // Iterate through all pointers in the event to normalize against the first.
336 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
337 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
338 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000340
341 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700342 // First, apply the current pointer's transform to update the coordinates into
343 // window space.
344 pointerCoords[pointerIndex].transform(currTransform);
345 // Next, apply the inverse transform of the normalized coordinates so the
346 // current coordinates are transformed into the normalized coordinate space.
347 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348 }
349
350 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800351 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
353 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
354 motionEntry.metaState, motionEntry.buttonState,
355 motionEntry.classification, motionEntry.edgeFlags,
356 motionEntry.xPrecision, motionEntry.yPrecision,
357 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
358 motionEntry.downTime, motionEntry.pointerCount,
359 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
360 0 /* yOffset */);
361
362 if (motionEntry.injectionState) {
363 combinedMotionEntry->injectionState = motionEntry.injectionState;
364 combinedMotionEntry->injectionState->refCount += 1;
365 }
366
367 std::unique_ptr<DispatchEntry> dispatchEntry =
368 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 inputTargetFlags, firstPointerTransform,
370 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371 combinedMotionEntry->release();
372 return dispatchEntry;
373}
374
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700375static void addGestureMonitors(const std::vector<Monitor>& monitors,
376 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
377 float yOffset = 0) {
378 if (monitors.empty()) {
379 return;
380 }
381 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
382 for (const Monitor& monitor : monitors) {
383 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
384 }
385}
386
Garfield Tan15601662020-09-22 15:32:38 -0700387static status_t openInputChannelPair(const std::string& name,
388 std::shared_ptr<InputChannel>& serverChannel,
389 std::unique_ptr<InputChannel>& clientChannel) {
390 std::unique_ptr<InputChannel> uniqueServerChannel;
391 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
392
393 serverChannel = std::move(uniqueServerChannel);
394 return result;
395}
396
Vishnu Nair958da932020-08-21 17:12:37 -0700397const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
398 switch (result) {
399 case InputDispatcher::FocusResult::OK:
400 return "Ok";
401 case InputDispatcher::FocusResult::NO_WINDOW:
402 return "Window not found";
403 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
404 return "Window not focusable";
405 case InputDispatcher::FocusResult::NOT_VISIBLE:
406 return "Window not visible";
407 }
408}
409
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500410template <typename T>
411static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
412 if (lhs == nullptr && rhs == nullptr) {
413 return true;
414 }
415 if (lhs == nullptr || rhs == nullptr) {
416 return false;
417 }
418 return *lhs == *rhs;
419}
420
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421// --- InputDispatcher ---
422
Garfield Tan00f511d2019-06-12 16:55:40 -0700423InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
424 : mPolicy(policy),
425 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700426 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800427 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700428 mAppSwitchSawKeyDown(false),
429 mAppSwitchDueTime(LONG_LONG_MAX),
430 mNextUnblockedEvent(nullptr),
431 mDispatchEnabled(false),
432 mDispatchFrozen(false),
433 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800434 // mInTouchMode will be initialized by the WindowManager to the default device config.
435 // To avoid leaking stack in case that call never comes, and for tests,
436 // initialize it here anyways.
437 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100438 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700439 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800441 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442
Yi Kong9b14ac62018-07-17 13:48:38 -0700443 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444
445 policy->getDispatcherConfiguration(&mConfig);
446}
447
448InputDispatcher::~InputDispatcher() {
449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451
452 resetKeyRepeatLocked();
453 releasePendingEventLocked();
454 drainInboundQueueLocked();
455 }
456
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700457 while (!mConnectionsByFd.empty()) {
458 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700459 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 }
461}
462
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700463status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700464 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700465 return ALREADY_EXISTS;
466 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700467 mThread = std::make_unique<InputThread>(
468 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
469 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700470}
471
472status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700473 if (mThread && mThread->isCallingThread()) {
474 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700475 return INVALID_OPERATION;
476 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700477 mThread.reset();
478 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700479}
480
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481void InputDispatcher::dispatchOnce() {
482 nsecs_t nextWakeupTime = LONG_LONG_MAX;
483 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800484 std::scoped_lock _l(mLock);
485 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486
487 // Run a dispatch loop if there are no pending commands.
488 // The dispatch loop might enqueue commands to run afterwards.
489 if (!haveCommandsLocked()) {
490 dispatchOnceInnerLocked(&nextWakeupTime);
491 }
492
493 // Run all pending commands if there are any.
494 // If any commands were run then force the next poll to wake up immediately.
495 if (runCommandsLockedInterruptible()) {
496 nextWakeupTime = LONG_LONG_MIN;
497 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700499 // If we are still waiting for ack on some events,
500 // we might have to wake up earlier to check if an app is anr'ing.
501 const nsecs_t nextAnrCheck = processAnrsLocked();
502 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
503
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800504 // We are about to enter an infinitely long sleep, because we have no commands or
505 // pending or queued events
506 if (nextWakeupTime == LONG_LONG_MAX) {
507 mDispatcherEnteredIdle.notify_all();
508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 } // release lock
510
511 // Wait for callback or timeout or wake. (make sure we round up, not down)
512 nsecs_t currentTime = now();
513 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
514 mLooper->pollOnce(timeoutMillis);
515}
516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700517/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500518 * Raise ANR if there is no focused window.
519 * Before the ANR is raised, do a final state check:
520 * 1. The currently focused application must be the same one we are waiting for.
521 * 2. Ensure we still don't have a focused window.
522 */
523void InputDispatcher::processNoFocusedWindowAnrLocked() {
524 // Check if the application that we are waiting for is still focused.
525 std::shared_ptr<InputApplicationHandle> focusedApplication =
526 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
527 if (focusedApplication == nullptr ||
528 focusedApplication->getApplicationToken() !=
529 mAwaitedFocusedApplication->getApplicationToken()) {
530 // Unexpected because we should have reset the ANR timer when focused application changed
531 ALOGE("Waited for a focused window, but focused application has already changed to %s",
532 focusedApplication->getName().c_str());
533 return; // The focused application has changed.
534 }
535
536 const sp<InputWindowHandle>& focusedWindowHandle =
537 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
538 if (focusedWindowHandle != nullptr) {
539 return; // We now have a focused window. No need for ANR.
540 }
541 onAnrLocked(mAwaitedFocusedApplication);
542}
543
544/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700545 * Check if any of the connections' wait queues have events that are too old.
546 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
547 * Return the time at which we should wake up next.
548 */
549nsecs_t InputDispatcher::processAnrsLocked() {
550 const nsecs_t currentTime = now();
551 nsecs_t nextAnrCheck = LONG_LONG_MAX;
552 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
553 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
554 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500555 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700556 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500557 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700558 return LONG_LONG_MIN;
559 } else {
560 // Keep waiting
561 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
562 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
563 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
564 }
565 }
566
567 // Check if any connection ANRs are due
568 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
569 if (currentTime < nextAnrCheck) { // most likely scenario
570 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
571 }
572
573 // If we reached here, we have an unresponsive connection.
574 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
575 if (connection == nullptr) {
576 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
577 return nextAnrCheck;
578 }
579 connection->responsive = false;
580 // Stop waking up for this unresponsive connection
581 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500582 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700583 return LONG_LONG_MIN;
584}
585
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500586std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700587 sp<InputWindowHandle> window = getWindowHandleLocked(token);
588 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500589 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500591 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700592}
593
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
595 nsecs_t currentTime = now();
596
Jeff Browndc5992e2014-04-11 01:27:26 -0700597 // Reset the key repeat timer whenever normal dispatch is suspended while the
598 // device is in a non-interactive state. This is to ensure that we abort a key
599 // repeat if the device is just coming out of sleep.
600 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 resetKeyRepeatLocked();
602 }
603
604 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
605 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100606 if (DEBUG_FOCUS) {
607 ALOGD("Dispatch frozen. Waiting some more.");
608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 return;
610 }
611
612 // Optimize latency of app switches.
613 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
614 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
615 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
616 if (mAppSwitchDueTime < *nextWakeupTime) {
617 *nextWakeupTime = mAppSwitchDueTime;
618 }
619
620 // Ready to start a new event.
621 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700622 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700623 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 if (isAppSwitchDue) {
625 // The inbound queue is empty so the app switch key we were waiting
626 // for will never arrive. Stop waiting for it.
627 resetPendingAppSwitchLocked(false);
628 isAppSwitchDue = false;
629 }
630
631 // Synthesize a key repeat if appropriate.
632 if (mKeyRepeatState.lastKeyEntry) {
633 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
634 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
635 } else {
636 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
637 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
638 }
639 }
640 }
641
642 // Nothing to do if there is no pending event.
643 if (!mPendingEvent) {
644 return;
645 }
646 } else {
647 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700648 mPendingEvent = mInboundQueue.front();
649 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 traceInboundQueueLengthLocked();
651 }
652
653 // Poke user activity for this event.
654 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700655 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 }
658
659 // Now we have an event to dispatch.
660 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700661 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 }
669
670 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700671 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 }
673
674 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700675 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 ConfigurationChangedEntry* typedEntry =
677 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
678 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 break;
681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700683 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
685 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700686 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700687 break;
688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100690 case EventEntry::Type::FOCUS: {
691 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
692 dispatchFocusLocked(currentTime, typedEntry);
693 done = true;
694 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
695 break;
696 }
697
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700698 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700699 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
700 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700701 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700702 resetPendingAppSwitchLocked(true);
703 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 } else if (dropReason == DropReason::NOT_DROPPED) {
705 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700706 }
707 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700708 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700709 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
712 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 }
714 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
715 break;
716 }
717
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700718 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700719 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
721 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700723 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700724 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700726 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
727 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 }
729 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
730 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
733
734 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700735 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700736 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
Michael Wright3a981722015-06-10 15:26:13 +0100738 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
740 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700741 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 }
743}
744
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700745/**
746 * Return true if the events preceding this incoming motion event should be dropped
747 * Return false otherwise (the default behaviour)
748 */
749bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700750 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700751 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700752
753 // Optimize case where the current application is unresponsive and the user
754 // decides to touch a window in a different application.
755 // If the application takes too long to catch up then we drop all events preceding
756 // the touch into the other window.
757 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700758 int32_t displayId = motionEntry.displayId;
759 int32_t x = static_cast<int32_t>(
760 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
761 int32_t y = static_cast<int32_t>(
762 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
763 sp<InputWindowHandle> touchedWindowHandle =
764 findTouchedWindowAtLocked(displayId, x, y, nullptr);
765 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700766 touchedWindowHandle->getApplicationToken() !=
767 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700768 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700769 ALOGI("Pruning input queue because user touched a different application while waiting "
770 "for %s",
771 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700772 return true;
773 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774
775 // Alternatively, maybe there's a gesture monitor that could handle this event
776 std::vector<TouchedMonitor> gestureMonitors =
777 findTouchedGestureMonitorsLocked(displayId, {});
778 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
779 sp<Connection> connection =
780 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000781 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700782 // This monitor could take more input. Drop all events preceding this
783 // event, so that gesture monitor could get a chance to receive the stream
784 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
785 "responsive gesture monitor that may handle the event",
786 mAwaitedFocusedApplication->getName().c_str());
787 return true;
788 }
789 }
790 }
791
792 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
793 // yet been processed by some connections, the dispatcher will wait for these motion
794 // events to be processed before dispatching the key event. This is because these motion events
795 // may cause a new window to be launched, which the user might expect to receive focus.
796 // To prevent waiting forever for such events, just send the key to the currently focused window
797 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
798 ALOGD("Received a new pointer down event, stop waiting for events to process and "
799 "just send the pending key event to the focused window.");
800 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700801 }
802 return false;
803}
804
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700806 bool needWake = mInboundQueue.empty();
807 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 traceInboundQueueLengthLocked();
809
810 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 // Optimize app switch latency.
813 // If the application takes too long to catch up then we drop all events preceding
814 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700815 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700817 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700819 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700824 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 mAppSwitchSawKeyDown = false;
826 needWake = true;
827 }
828 }
829 }
830 break;
831 }
832
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700833 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700834 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
835 mNextUnblockedEvent = entry;
836 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100840 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700841 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
842 break;
843 }
844 case EventEntry::Type::CONFIGURATION_CHANGED:
845 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700846 // nothing to do
847 break;
848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850
851 return needWake;
852}
853
854void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
855 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700856 mRecentQueue.push_back(entry);
857 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
858 mRecentQueue.front()->release();
859 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 }
861}
862
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700864 int32_t y, TouchState* touchState,
865 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700867 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
868 LOG_ALWAYS_FATAL(
869 "Must provide a valid touch state if adding portal windows or outside targets");
870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700872 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800873 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 const InputWindowInfo* windowInfo = windowHandle->getInfo();
875 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100876 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877
878 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100879 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
880 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
881 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800883 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 if (portalToDisplayId != ADISPLAY_ID_NONE &&
885 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800886 if (addPortalWindows) {
887 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700888 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800889 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700890 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 // Found window.
894 return windowHandle;
895 }
896 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800897
Michael Wright44753b12020-07-08 13:48:11 +0100898 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700899 touchState->addOrUpdateWindow(windowHandle,
900 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
901 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907}
908
Garfield Tane84e6f92019-08-29 17:28:41 -0700909std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700910 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000911 std::vector<TouchedMonitor> touchedMonitors;
912
913 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
914 addGestureMonitors(monitors, touchedMonitors);
915 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
916 const InputWindowInfo* windowInfo = portalWindow->getInfo();
917 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
919 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000920 }
921 return touchedMonitors;
922}
923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700924void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 const char* reason;
926 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700927 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 reason = "inbound event was dropped because the policy consumed it";
932 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700933 case DropReason::DISABLED:
934 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 ALOGI("Dropped event because input dispatch is disabled.");
936 }
937 reason = "inbound event was dropped because input dispatch is disabled";
938 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700939 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 ALOGI("Dropped event because of pending overdue app switch.");
941 reason = "inbound event was dropped because of pending overdue app switch";
942 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700943 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 ALOGI("Dropped event because the current application is not responding and the user "
945 "has started interacting with a different application.");
946 reason = "inbound event was dropped because the current application is not responding "
947 "and the user has started interacting with a different application";
948 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700949 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 ALOGI("Dropped event because it is stale.");
951 reason = "inbound event was dropped because it is stale";
952 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 case DropReason::NOT_DROPPED: {
954 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700959 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700960 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
962 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700965 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700966 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
967 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
969 synthesizeCancelationEventsForAllConnectionsLocked(options);
970 } else {
971 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
972 synthesizeCancelationEventsForAllConnectionsLocked(options);
973 }
974 break;
975 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100976 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700977 case EventEntry::Type::CONFIGURATION_CHANGED:
978 case EventEntry::Type::DEVICE_RESET: {
979 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
980 break;
981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983}
984
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800985static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
987 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988}
989
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700990bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
991 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
992 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
993 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994}
995
996bool InputDispatcher::isAppSwitchPendingLocked() {
997 return mAppSwitchDueTime != LONG_LONG_MAX;
998}
999
1000void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1001 mAppSwitchDueTime = LONG_LONG_MAX;
1002
1003#if DEBUG_APP_SWITCH
1004 if (handled) {
1005 ALOGD("App switch has arrived.");
1006 } else {
1007 ALOGD("App switch was abandoned.");
1008 }
1009#endif
1010}
1011
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001013 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014}
1015
1016bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001017 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 return false;
1019 }
1020
1021 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001022 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001023 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001025 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
1027 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001028 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 return true;
1030}
1031
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001032void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1033 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034}
1035
1036void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001037 while (!mInboundQueue.empty()) {
1038 EventEntry* entry = mInboundQueue.front();
1039 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 releaseInboundEventLocked(entry);
1041 }
1042 traceInboundQueueLengthLocked();
1043}
1044
1045void InputDispatcher::releasePendingEventLocked() {
1046 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001048 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050}
1051
1052void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1053 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001054 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055#if DEBUG_DISPATCH_CYCLE
1056 ALOGD("Injected inbound event was dropped.");
1057#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001058 setInjectionResult(entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 addRecentEventLocked(entry);
1064 entry->release();
1065}
1066
1067void InputDispatcher::resetKeyRepeatLocked() {
1068 if (mKeyRepeatState.lastKeyEntry) {
1069 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072}
1073
Garfield Tane84e6f92019-08-29 17:28:41 -07001074KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1076
1077 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001078 uint32_t policyFlags = entry->policyFlags &
1079 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (entry->refCount == 1) {
1081 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001082 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 entry->eventTime = currentTime;
1084 entry->policyFlags = policyFlags;
1085 entry->repeatCount += 1;
1086 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001088 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001089 entry->displayId, policyFlags, entry->action, entry->flags,
1090 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092
1093 mKeyRepeatState.lastKeyEntry = newEntry;
1094 entry->release();
1095
1096 entry = newEntry;
1097 }
1098 entry->syntheticRepeat = true;
1099
1100 // Increment reference count since we keep a reference to the event in
1101 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1102 entry->refCount += 1;
1103
1104 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1105 return entry;
1106}
1107
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1109 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001111 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#endif
1113
1114 // Reset key repeating in case a keyboard device was added or removed or something.
1115 resetKeyRepeatLocked();
1116
1117 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001118 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1119 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001121 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 return true;
1123}
1124
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001127 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129#endif
1130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 options.deviceId = entry->deviceId;
1133 synthesizeCancelationEventsForAllConnectionsLocked(options);
1134 return true;
1135}
1136
Vishnu Nairad321cd2020-08-20 16:40:21 -07001137void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001138 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001139 if (mPendingEvent != nullptr) {
1140 // Move the pending event to the front of the queue. This will give the chance
1141 // for the pending event to get dispatched to the newly focused window
1142 mInboundQueue.push_front(mPendingEvent);
1143 mPendingEvent = nullptr;
1144 }
1145
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001146 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001147 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001148
1149 // This event should go to the front of the queue, but behind all other focus events
1150 // Find the last focus event, and insert right after it
1151 std::deque<EventEntry*>::reverse_iterator it =
1152 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1153 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1154
1155 // Maintain the order of focus events. Insert the entry after all other focus events.
1156 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001157}
1158
1159void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001160 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001161 if (channel == nullptr) {
1162 return; // Window has gone away
1163 }
1164 InputTarget target;
1165 target.inputChannel = channel;
1166 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1167 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001168 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1169 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001170 std::string reason = std::string("reason=").append(entry->reason);
1171 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 dispatchEventLocked(currentTime, entry, {target});
1173}
1174
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 if (!entry->dispatchInProgress) {
1179 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1180 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1181 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1182 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001183 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 // We have seen two identical key downs in a row which indicates that the device
1185 // driver is automatically generating key repeats itself. We take note of the
1186 // repeat here, but we disable our own next key repeat timer since it is clear that
1187 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001188 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1189 // Make sure we don't get key down from a different device. If a different
1190 // device Id has same key pressed down, the new device Id will replace the
1191 // current one to hold the key repeat with repeat count reset.
1192 // In the future when got a KEY_UP on the device id, drop it and do not
1193 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1195 resetKeyRepeatLocked();
1196 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1197 } else {
1198 // Not a repeat. Save key down state in case we do see a repeat later.
1199 resetKeyRepeatLocked();
1200 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1201 }
1202 mKeyRepeatState.lastKeyEntry = entry;
1203 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001204 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1205 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1206 // The stale device releases the key, reset staleDeviceId.
1207#if DEBUG_INBOUND_EVENT_DETAILS
1208 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1209#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 resetKeyRepeatLocked();
1212 }
1213
1214 if (entry->repeatCount == 1) {
1215 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1216 } else {
1217 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1218 }
1219
1220 entry->dispatchInProgress = true;
1221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001222 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224
1225 // Handle case where the policy asked us to try again later last time.
1226 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1227 if (currentTime < entry->interceptKeyWakeupTime) {
1228 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1229 *nextWakeupTime = entry->interceptKeyWakeupTime;
1230 }
1231 return false; // wait until next wakeup
1232 }
1233 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1234 entry->interceptKeyWakeupTime = 0;
1235 }
1236
1237 // Give the policy a chance to intercept the key.
1238 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1239 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001240 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001241 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001242 sp<IBinder> focusedWindowToken =
1243 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1244 if (focusedWindowToken != nullptr) {
1245 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
1247 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001248 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 entry->refCount += 1;
1250 return false; // wait for the command to run
1251 } else {
1252 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1253 }
1254 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001255 if (*dropReason == DropReason::NOT_DROPPED) {
1256 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
1258 }
1259
1260 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001261 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001263 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1264 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001265 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 return true;
1267 }
1268
1269 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001270 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001272 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001273 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 return false;
1275 }
1276
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001277 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001278 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
1285 // Dispatch the key.
1286 dispatchEventLocked(currentTime, entry, inputTargets);
1287 return true;
1288}
1289
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001290void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001292 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1294 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1296 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1297 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298#endif
1299}
1300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1302 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001303 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 entry->dispatchInProgress = true;
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
1310
1311 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001314 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1315 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 return true;
1317 }
1318
1319 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1320
1321 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001322 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323
1324 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001325 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 if (isPointerEvent) {
1327 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001329 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 } else {
1332 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001333 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001336 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 return false;
1338 }
1339
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001340 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001341 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001342 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1343 return true;
1344 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001345 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001346 CancelationOptions::Mode mode(isPointerEvent
1347 ? CancelationOptions::CANCEL_POINTER_EVENTS
1348 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1349 CancelationOptions options(mode, "input event injection failed");
1350 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 return true;
1352 }
1353
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001354 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001355 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001357 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001358 std::unordered_map<int32_t, TouchState>::iterator it =
1359 mTouchStatesByDisplay.find(entry->displayId);
1360 if (it != mTouchStatesByDisplay.end()) {
1361 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001362 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001363 // The event has gone through these portal windows, so we add monitoring targets of
1364 // the corresponding displays as well.
1365 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001366 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001367 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001369 }
1370 }
1371 }
1372 }
1373
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 // Dispatch the motion.
1375 if (conflictingPointerActions) {
1376 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 synthesizeCancelationEventsForAllConnectionsLocked(options);
1379 }
1380 dispatchEventLocked(currentTime, entry, inputTargets);
1381 return true;
1382}
1383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001384void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001386 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 ", policyFlags=0x%x, "
1388 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1389 "metaState=0x%x, buttonState=0x%x,"
1390 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1392 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1393 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 "x=%f, y=%f, pressure=%f, size=%f, "
1398 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1399 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1401 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1402 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1403 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1404 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1405 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1406 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1407 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1408 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1409 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411#endif
1412}
1413
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1415 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001416 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417#if DEBUG_DISPATCH_CYCLE
1418 ALOGD("dispatchEventToCurrentInputTargets");
1419#endif
1420
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001421 updateInteractionTokensLocked(*eventEntry, inputTargets);
1422
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1424
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001427 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001428 sp<Connection> connection =
1429 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001430 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001431 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001433 if (DEBUG_FOCUS) {
1434 ALOGD("Dropping event delivery to target with channel '%s' because it "
1435 "is no longer registered with the input dispatcher.",
1436 inputTarget.inputChannel->getName().c_str());
1437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
1439 }
1440}
1441
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001442void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1443 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1444 // If the policy decides to close the app, we will get a channel removal event via
1445 // unregisterInputChannel, and will clean up the connection that way. We are already not
1446 // sending new pointers to the connection when it blocked, but focused events will continue to
1447 // pile up.
1448 ALOGW("Canceling events for %s because it is unresponsive",
1449 connection->inputChannel->getName().c_str());
1450 if (connection->status == Connection::STATUS_NORMAL) {
1451 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1452 "application not responding");
1453 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455}
1456
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001457void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001458 if (DEBUG_FOCUS) {
1459 ALOGD("Resetting ANR timeouts.");
1460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
1462 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001464 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465}
1466
Tiger Huang721e26f2018-07-24 22:26:19 +08001467/**
1468 * Get the display id that the given event should go to. If this event specifies a valid display id,
1469 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1470 * Focused display is the display that the user most recently interacted with.
1471 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001472int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001473 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001474 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001475 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1477 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 break;
1479 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001480 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1482 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 break;
1484 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001485 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001486 case EventEntry::Type::CONFIGURATION_CHANGED:
1487 case EventEntry::Type::DEVICE_RESET: {
1488 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 return ADISPLAY_ID_NONE;
1490 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001491 }
1492 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1493}
1494
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001495bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1496 const char* focusedWindowName) {
1497 if (mAnrTracker.empty()) {
1498 // already processed all events that we waited for
1499 mKeyIsWaitingForEventsTimeout = std::nullopt;
1500 return false;
1501 }
1502
1503 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1504 // Start the timer
1505 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1506 "focus to change",
1507 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001508 mKeyIsWaitingForEventsTimeout = currentTime +
1509 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1510 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001511 return true;
1512 }
1513
1514 // We still have pending events, and already started the timer
1515 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1516 return true; // Still waiting
1517 }
1518
1519 // Waited too long, and some connection still hasn't processed all motions
1520 // Just send the key to the focused window
1521 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1522 focusedWindowName);
1523 mKeyIsWaitingForEventsTimeout = std::nullopt;
1524 return false;
1525}
1526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1528 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1529 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001530 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531
Tiger Huang721e26f2018-07-24 22:26:19 +08001532 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001533 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001534 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001535 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1536
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 // If there is no currently focused window and no focused application
1538 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001539 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1540 ALOGI("Dropping %s event because there is no focused window or focused application in "
1541 "display %" PRId32 ".",
1542 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001543 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001546 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1547 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1548 // start interacting with another application via touch (app switch). This code can be removed
1549 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1550 // an app is expected to have a focused window.
1551 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1552 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1553 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001554 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1555 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1556 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001557 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001558 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001559 ALOGW("Waiting because no window has focus but %s may eventually add a "
1560 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001561 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001562 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001564 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1565 // Already raised ANR. Drop the event
1566 ALOGE("Dropping %s event because there is no focused window",
1567 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001568 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001569 } else {
1570 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001572 }
1573 }
1574
1575 // we have a valid, non-null focused window
1576 resetNoFocusedWindowTimeoutLocked();
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001579 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001580 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001583 if (focusedWindowHandle->getInfo()->paused) {
1584 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001586 }
1587
1588 // If the event is a key event, then we must wait for all previous events to
1589 // complete before delivering it because previous events may have the
1590 // side-effect of transferring focus to a different window and we want to
1591 // ensure that the following keys are sent to the new window.
1592 //
1593 // Suppose the user touches a button in a window then immediately presses "A".
1594 // If the button causes a pop-up window to appear then we want to ensure that
1595 // the "A" key is delivered to the new pop-up window. This is because users
1596 // often anticipate pending UI changes when typing on a keyboard.
1597 // To obtain this behavior, we must serialize key events with respect to all
1598 // prior input events.
1599 if (entry.type == EventEntry::Type::KEY) {
1600 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1601 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001602 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605
1606 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001607 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1609 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610
1611 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613}
1614
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001615/**
1616 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1617 * that are currently unresponsive.
1618 */
1619std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1620 const std::vector<TouchedMonitor>& monitors) const {
1621 std::vector<TouchedMonitor> responsiveMonitors;
1622 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1623 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1624 sp<Connection> connection = getConnectionLocked(
1625 monitor.monitor.inputChannel->getConnectionToken());
1626 if (connection == nullptr) {
1627 ALOGE("Could not find connection for monitor %s",
1628 monitor.monitor.inputChannel->getName().c_str());
1629 return false;
1630 }
1631 if (!connection->responsive) {
1632 ALOGW("Unresponsive monitor %s will not get the new gesture",
1633 connection->inputChannel->getName().c_str());
1634 return false;
1635 }
1636 return true;
1637 });
1638 return responsiveMonitors;
1639}
1640
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001641InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1642 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1643 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001644 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 enum InjectionPermission {
1646 INJECTION_PERMISSION_UNKNOWN,
1647 INJECTION_PERMISSION_GRANTED,
1648 INJECTION_PERMISSION_DENIED
1649 };
1650
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 // For security reasons, we defer updating the touch state until we are sure that
1652 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 int32_t displayId = entry.displayId;
1654 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1656
1657 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001660 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1661 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001663 // Copy current touch state into tempTouchState.
1664 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1665 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001666 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001667 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001668 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1669 mTouchStatesByDisplay.find(displayId);
1670 if (oldStateIt != mTouchStatesByDisplay.end()) {
1671 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001672 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001673 }
1674
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001675 bool isSplit = tempTouchState.split;
1676 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1677 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1678 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001679 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1680 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1681 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1682 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1683 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001684 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 bool wrongDevice = false;
1686 if (newGesture) {
1687 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001688 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001689 ALOGI("Dropping event because a pointer for a different device is already down "
1690 "in display %" PRId32,
1691 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001692 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001693 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 switchedDevice = false;
1695 wrongDevice = true;
1696 goto Failed;
1697 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001698 tempTouchState.reset();
1699 tempTouchState.down = down;
1700 tempTouchState.deviceId = entry.deviceId;
1701 tempTouchState.source = entry.source;
1702 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001704 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001705 ALOGI("Dropping move event because a pointer for a different device is already active "
1706 "in display %" PRId32,
1707 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001708 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001709 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001710 switchedDevice = false;
1711 wrongDevice = true;
1712 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714
1715 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1716 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1717
Garfield Tan00f511d2019-06-12 16:55:40 -07001718 int32_t x;
1719 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001721 // Always dispatch mouse events to cursor position.
1722 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001723 x = int32_t(entry.xCursorPosition);
1724 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001725 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001726 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1727 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001728 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001730 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001731 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1732 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001733
1734 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001735 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001739 if (newTouchedWindowHandle != nullptr &&
1740 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001741 // New window supports splitting, but we should never split mouse events.
1742 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 } else if (isSplit) {
1744 // New window does not support splitting but we have already split events.
1745 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001746 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748
1749 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001750 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001752 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001753 }
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1756 ALOGI("Not sending touch event to %s because it is paused",
1757 newTouchedWindowHandle->getName().c_str());
1758 newTouchedWindowHandle = nullptr;
1759 }
1760
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001761 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001762 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001763 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1764 if (!isResponsive) {
1765 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1767 newTouchedWindowHandle = nullptr;
1768 }
1769 }
1770
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001771 // Drop events that can't be trusted due to occlusion
1772 if (newTouchedWindowHandle != nullptr &&
1773 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1774 TouchOcclusionInfo occlusionInfo =
1775 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001776 if (!isTouchTrustedLocked(occlusionInfo)) {
1777 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1778 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1779 ALOGW("Dropping untrusted touch event due to %s/%d",
1780 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1781 newTouchedWindowHandle = nullptr;
1782 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001783 }
1784 }
1785
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 // Also don't send the new touch event to unresponsive gesture monitors
1787 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1788
Michael Wright3dd60e22019-03-27 22:06:44 +00001789 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1790 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 "(%d, %d) in display %" PRId32 ".",
1792 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001794 goto Failed;
1795 }
1796
1797 if (newTouchedWindowHandle != nullptr) {
1798 // Set target flags.
1799 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1800 if (isSplit) {
1801 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001803 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1804 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1805 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1806 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1807 }
1808
1809 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001810 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1811 newHoverWindowHandle = nullptr;
1812 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001814 }
1815
1816 // Update the temporary touch state.
1817 BitSet32 pointerIds;
1818 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001820 pointerIds.markBit(pointerId);
1821 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001825 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 } else {
1827 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1828
1829 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001831 if (DEBUG_FOCUS) {
1832 ALOGD("Dropping event because the pointer is not down or we previously "
1833 "dropped the pointer down event in display %" PRId32,
1834 displayId);
1835 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 goto Failed;
1838 }
1839
1840 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001843 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1844 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
1846 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001848 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001849 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1850 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001851 if (DEBUG_FOCUS) {
1852 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1853 oldTouchedWindowHandle->getName().c_str(),
1854 newTouchedWindowHandle->getName().c_str(), displayId);
1855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1858 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1859 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 // Make a slippery entrance into the new window.
1862 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1863 isSplit = true;
1864 }
1865
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001866 int32_t targetFlags =
1867 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 if (isSplit) {
1869 targetFlags |= InputTarget::FLAG_SPLIT;
1870 }
1871 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1872 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1873 }
1874
1875 BitSet32 pointerIds;
1876 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001877 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001879 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
1881 }
1882 }
1883
1884 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001885 // Let the previous window know that the hover sequence is over, unless we already did it
1886 // when dispatching it as is to newTouchedWindowHandle.
1887 if (mLastHoverWindowHandle != nullptr &&
1888 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1889 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890#if DEBUG_HOVER
1891 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1895 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897
Garfield Tandf26e862020-07-01 20:18:19 -07001898 // Let the new window know that the hover sequence is starting, unless we already did it
1899 // when dispatching it as is to newTouchedWindowHandle.
1900 if (newHoverWindowHandle != nullptr &&
1901 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1902 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903#if DEBUG_HOVER
1904 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001905 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1908 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1909 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911 }
1912
1913 // Check permission to inject into all touched foreground windows and ensure there
1914 // is at least one touched foreground window.
1915 {
1916 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1919 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001920 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 injectionPermission = INJECTION_PERMISSION_DENIED;
1923 goto Failed;
1924 }
1925 }
1926 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001927 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001928 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001929 ALOGI("Dropping event because there is no touched foreground window in display "
1930 "%" PRId32 " or gesture monitor to receive it.",
1931 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 goto Failed;
1934 }
1935
1936 // Permission granted to injection into all touched foreground windows.
1937 injectionPermission = INJECTION_PERMISSION_GRANTED;
1938 }
1939
1940 // Check whether windows listening for outside touches are owned by the same UID. If it is
1941 // set the policy flag that we will not reveal coordinate information to this window.
1942 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1943 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001945 if (foregroundWindowHandle) {
1946 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001948 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1949 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1950 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001951 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1952 InputTarget::FLAG_ZERO_COORDS,
1953 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
1956 }
1957 }
1958 }
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // If this is the first pointer going down and the touched window has a wallpaper
1961 // then also add the touched wallpaper windows so they are locked in for the duration
1962 // of the touch gesture.
1963 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1964 // engine only supports touch events. We would need to add a mechanism similar
1965 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1966 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1967 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001968 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001970 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001971 getWindowHandlesLocked(displayId);
1972 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001975 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001976 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001977 .addOrUpdateWindow(windowHandle,
1978 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1979 InputTarget::
1980 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1981 InputTarget::FLAG_DISPATCH_AS_IS,
1982 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
1984 }
1985 }
1986 }
1987
1988 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
1995
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001997 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001998 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001999 }
2000
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 // Drop the outside or hover touch windows since we will not care about them
2002 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005Failed:
2006 // Check injection permission once and for all.
2007 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002008 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 injectionPermission = INJECTION_PERMISSION_GRANTED;
2010 } else {
2011 injectionPermission = INJECTION_PERMISSION_DENIED;
2012 }
2013 }
2014
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002015 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2016 return injectionResult;
2017 }
2018
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002020 if (!wrongDevice) {
2021 if (switchedDevice) {
2022 if (DEBUG_FOCUS) {
2023 ALOGD("Conflicting pointer actions: Switched to a different device.");
2024 }
2025 *outConflictingPointerActions = true;
2026 }
2027
2028 if (isHoverAction) {
2029 // Started hovering, therefore no longer down.
2030 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002031 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002032 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2033 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 *outConflictingPointerActions = true;
2036 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002037 tempTouchState.reset();
2038 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2039 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2040 tempTouchState.deviceId = entry.deviceId;
2041 tempTouchState.source = entry.source;
2042 tempTouchState.displayId = displayId;
2043 }
2044 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2045 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2046 // All pointers up or canceled.
2047 tempTouchState.reset();
2048 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2049 // First pointer went down.
2050 if (oldState && oldState->down) {
2051 if (DEBUG_FOCUS) {
2052 ALOGD("Conflicting pointer actions: Down received while already down.");
2053 }
2054 *outConflictingPointerActions = true;
2055 }
2056 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2057 // One pointer went up.
2058 if (isSplit) {
2059 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2060 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002062 for (size_t i = 0; i < tempTouchState.windows.size();) {
2063 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2064 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2065 touchedWindow.pointerIds.clearBit(pointerId);
2066 if (touchedWindow.pointerIds.isEmpty()) {
2067 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2068 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002071 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002073 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002074 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002075
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002076 // Save changes unless the action was scroll in which case the temporary touch
2077 // state was only valid for this one action.
2078 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2079 if (tempTouchState.displayId >= 0) {
2080 mTouchStatesByDisplay[displayId] = tempTouchState;
2081 } else {
2082 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002086 // Update hover state.
2087 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 return injectionResult;
2091}
2092
2093void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 int32_t targetFlags, BitSet32 pointerIds,
2095 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002096 std::vector<InputTarget>::iterator it =
2097 std::find_if(inputTargets.begin(), inputTargets.end(),
2098 [&windowHandle](const InputTarget& inputTarget) {
2099 return inputTarget.inputChannel->getConnectionToken() ==
2100 windowHandle->getToken();
2101 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002102
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002103 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002104
2105 if (it == inputTargets.end()) {
2106 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002107 std::shared_ptr<InputChannel> inputChannel =
2108 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002109 if (inputChannel == nullptr) {
2110 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2111 return;
2112 }
2113 inputTarget.inputChannel = inputChannel;
2114 inputTarget.flags = targetFlags;
2115 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2116 inputTargets.push_back(inputTarget);
2117 it = inputTargets.end() - 1;
2118 }
2119
2120 ALOG_ASSERT(it->flags == targetFlags);
2121 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2122
chaviw1ff3d1e2020-07-01 15:53:47 -07002123 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124}
2125
Michael Wright3dd60e22019-03-27 22:06:44 +00002126void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 int32_t displayId, float xOffset,
2128 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002129 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2130 mGlobalMonitorsByDisplay.find(displayId);
2131
2132 if (it != mGlobalMonitorsByDisplay.end()) {
2133 const std::vector<Monitor>& monitors = it->second;
2134 for (const Monitor& monitor : monitors) {
2135 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138}
2139
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2141 float yOffset,
2142 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 InputTarget target;
2144 target.inputChannel = monitor.inputChannel;
2145 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002146 ui::Transform t;
2147 t.set(xOffset, yOffset);
2148 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 inputTargets.push_back(target);
2150}
2151
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 const InjectionState* injectionState) {
2154 if (injectionState &&
2155 (windowHandle == nullptr ||
2156 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2157 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002158 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 "owned by uid %d",
2161 injectionState->injectorPid, injectionState->injectorUid,
2162 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 } else {
2164 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
2167 return false;
2168 }
2169 return true;
2170}
2171
Robert Carrc9bf1d32020-04-13 17:21:08 -07002172/**
2173 * Indicate whether one window handle should be considered as obscuring
2174 * another window handle. We only check a few preconditions. Actually
2175 * checking the bounds is left to the caller.
2176 */
2177static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2178 const sp<InputWindowHandle>& otherHandle) {
2179 // Compare by token so cloned layers aren't counted
2180 if (haveSameToken(windowHandle, otherHandle)) {
2181 return false;
2182 }
2183 auto info = windowHandle->getInfo();
2184 auto otherInfo = otherHandle->getInfo();
2185 if (!otherInfo->visible) {
2186 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002187 } else if (info->ownerUid == otherInfo->ownerUid) {
2188 // If ownerUid is the same we don't generate occlusion events as there
2189 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002190 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002191 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002192 return false;
2193 } else if (otherInfo->displayId != info->displayId) {
2194 return false;
2195 }
2196 return true;
2197}
2198
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002199/**
2200 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2201 * untrusted, one should check:
2202 *
2203 * 1. If result.hasBlockingOcclusion is true.
2204 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2205 * BLOCK_UNTRUSTED.
2206 *
2207 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2208 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2209 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2210 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2211 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2212 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2213 *
2214 * If neither of those is true, then it means the touch can be allowed.
2215 */
2216InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2217 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2218 int32_t displayId = windowHandle->getInfo()->displayId;
2219 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2220 TouchOcclusionInfo info;
2221 info.hasBlockingOcclusion = false;
2222 info.obscuringOpacity = 0;
2223 info.obscuringUid = -1;
2224 std::map<int32_t, float> opacityByUid;
2225 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2226 if (windowHandle == otherHandle) {
2227 break; // All future windows are below us. Exit early.
2228 }
2229 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2230 if (canBeObscuredBy(windowHandle, otherHandle) &&
2231 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2232 otherInfo->frameContainsPoint(x, y)) {
2233 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2234 // we perform the checks below to see if the touch can be propagated or not based on the
2235 // window's touch occlusion mode
2236 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2237 info.hasBlockingOcclusion = true;
2238 info.obscuringUid = otherInfo->ownerUid;
2239 info.obscuringPackage = otherInfo->packageName;
2240 break;
2241 }
2242 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2243 uint32_t uid = otherInfo->ownerUid;
2244 float opacity =
2245 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2246 // Given windows A and B:
2247 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2248 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2249 opacityByUid[uid] = opacity;
2250 if (opacity > info.obscuringOpacity) {
2251 info.obscuringOpacity = opacity;
2252 info.obscuringUid = uid;
2253 info.obscuringPackage = otherInfo->packageName;
2254 }
2255 }
2256 }
2257 }
2258 return info;
2259}
2260
2261bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2262 if (occlusionInfo.hasBlockingOcclusion) {
2263 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2264 occlusionInfo.obscuringUid);
2265 return false;
2266 }
2267 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2268 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2269 "%.2f, maximum allowed = %.2f)",
2270 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2271 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2272 return false;
2273 }
2274 return true;
2275}
2276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2278 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002280 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002281 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002282 if (windowHandle == otherHandle) {
2283 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002286 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002287 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 return true;
2289 }
2290 }
2291 return false;
2292}
2293
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002294bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2295 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002296 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002297 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002298 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002299 if (windowHandle == otherHandle) {
2300 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002301 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002302 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002303 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002304 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002305 return true;
2306 }
2307 }
2308 return false;
2309}
2310
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002311std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002312 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002314 if (applicationHandle != nullptr) {
2315 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002316 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 } else {
2318 return applicationHandle->getName();
2319 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002320 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002321 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002323 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325}
2326
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002327void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002328 if (eventEntry.type == EventEntry::Type::FOCUS) {
2329 // Focus events are passed to apps, but do not represent user activity.
2330 return;
2331 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002332 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002333 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002334 if (focusedWindowHandle != nullptr) {
2335 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002336 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002338 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339#endif
2340 return;
2341 }
2342 }
2343
2344 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002345 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002346 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002347 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2348 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 return;
2350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002352 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 eventType = USER_ACTIVITY_EVENT_TOUCH;
2354 }
2355 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002357 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002358 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2359 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 return;
2361 }
2362 eventType = USER_ACTIVITY_EVENT_BUTTON;
2363 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002365 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002366 case EventEntry::Type::CONFIGURATION_CHANGED:
2367 case EventEntry::Type::DEVICE_RESET: {
2368 LOG_ALWAYS_FATAL("%s events are not user activity",
2369 EventEntry::typeToString(eventEntry.type));
2370 break;
2371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 }
2373
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002374 std::unique_ptr<CommandEntry> commandEntry =
2375 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002376 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002378 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379}
2380
2381void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 const sp<Connection>& connection,
2383 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002384 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002385 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002386 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002387 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002388 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002389 ATRACE_NAME(message.c_str());
2390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391#if DEBUG_DISPATCH_CYCLE
2392 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002393 "globalScaleFactor=%f, pointerIds=0x%x %s",
2394 connection->getInputChannelName().c_str(), inputTarget.flags,
2395 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2396 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397#endif
2398
2399 // Skip this event if the connection status is not normal.
2400 // We don't want to enqueue additional outbound events if the connection is broken.
2401 if (connection->status != Connection::STATUS_NORMAL) {
2402#if DEBUG_DISPATCH_CYCLE
2403 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405#endif
2406 return;
2407 }
2408
2409 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002410 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2411 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2412 "Entry type %s should not have FLAG_SPLIT",
2413 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002415 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002416 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002418 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 if (!splitMotionEntry) {
2420 return; // split event was dropped
2421 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002422 if (DEBUG_FOCUS) {
2423 ALOGD("channel '%s' ~ Split motion event.",
2424 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002425 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002426 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 splitMotionEntry->release();
2429 return;
2430 }
2431 }
2432
2433 // Not splitting. Enqueue dispatch entries for the event as is.
2434 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2435}
2436
2437void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 const sp<Connection>& connection,
2439 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002440 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002441 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002442 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002443 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002444 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002445 ATRACE_NAME(message.c_str());
2446 }
2447
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002448 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449
2450 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002451 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002453 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002454 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002455 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002457 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002459 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002461 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002462 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463
2464 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002465 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 startDispatchCycleLocked(currentTime, connection);
2467 }
2468}
2469
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002470void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2471 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002472 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002474 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2476 connection->getInputChannelName().c_str(),
2477 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002478 ATRACE_NAME(message.c_str());
2479 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002480 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 if (!(inputTargetFlags & dispatchMode)) {
2482 return;
2483 }
2484 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2485
2486 // This is a new event.
2487 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002488 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002489 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002491 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2492 // different EventEntry than what was passed in.
2493 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002495 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002496 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002497 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002498 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002499 dispatchEntry->resolvedAction = keyEntry.action;
2500 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2503 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2506 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 return; // skip the inconsistent event
2509 }
2510 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002513 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002514 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002515 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2516 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2517 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2518 static_cast<int32_t>(IdGenerator::Source::OTHER);
2519 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2521 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2522 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2523 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2524 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2525 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2526 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2527 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2528 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2529 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2530 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002531 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002532 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 }
2534 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002535 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2536 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2539 "event",
2540 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002545 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2547 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2548 }
2549 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2550 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2554 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2557 "event",
2558 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 return; // skip the inconsistent event
2561 }
2562
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002563 dispatchEntry->resolvedEventId =
2564 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2565 ? mIdGenerator.nextId()
2566 : motionEntry.id;
2567 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2568 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2569 ") to MotionEvent(id=0x%" PRIx32 ").",
2570 motionEntry.id, dispatchEntry->resolvedEventId);
2571 ATRACE_NAME(message.c_str());
2572 }
2573
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002574 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002575 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576
2577 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002579 case EventEntry::Type::FOCUS: {
2580 break;
2581 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002582 case EventEntry::Type::CONFIGURATION_CHANGED:
2583 case EventEntry::Type::DEVICE_RESET: {
2584 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002585 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002586 break;
2587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589
2590 // Remember that we are waiting for this dispatch to complete.
2591 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002592 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
2594
2595 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002596 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002597 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002598}
2599
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002600/**
2601 * This function is purely for debugging. It helps us understand where the user interaction
2602 * was taking place. For example, if user is touching launcher, we will see a log that user
2603 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2604 * We will see both launcher and wallpaper in that list.
2605 * Once the interaction with a particular set of connections starts, no new logs will be printed
2606 * until the set of interacted connections changes.
2607 *
2608 * The following items are skipped, to reduce the logspam:
2609 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2610 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2611 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2612 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2613 * Both of those ACTION_UP events would not be logged
2614 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2615 * will not be logged. This is omitted to reduce the amount of data printed.
2616 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2617 * gesture monitor is the only connection receiving the remainder of the gesture.
2618 */
2619void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2620 const std::vector<InputTarget>& targets) {
2621 // Skip ACTION_UP events, and all events other than keys and motions
2622 if (entry.type == EventEntry::Type::KEY) {
2623 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2624 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2625 return;
2626 }
2627 } else if (entry.type == EventEntry::Type::MOTION) {
2628 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2629 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2630 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2631 return;
2632 }
2633 } else {
2634 return; // Not a key or a motion
2635 }
2636
2637 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2638 std::vector<sp<Connection>> newConnections;
2639 for (const InputTarget& target : targets) {
2640 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2641 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2642 continue; // Skip windows that receive ACTION_OUTSIDE
2643 }
2644
2645 sp<IBinder> token = target.inputChannel->getConnectionToken();
2646 sp<Connection> connection = getConnectionLocked(token);
2647 if (connection == nullptr || connection->monitor) {
2648 continue; // We only need to keep track of the non-monitor connections.
2649 }
2650 newConnectionTokens.insert(std::move(token));
2651 newConnections.emplace_back(connection);
2652 }
2653 if (newConnectionTokens == mInteractionConnectionTokens) {
2654 return; // no change
2655 }
2656 mInteractionConnectionTokens = newConnectionTokens;
2657
2658 std::string windowList;
2659 for (const sp<Connection>& connection : newConnections) {
2660 windowList += connection->getWindowName() + ", ";
2661 }
2662 std::string message = "Interaction with windows: " + windowList;
2663 if (windowList.empty()) {
2664 message += "<none>";
2665 }
2666 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2667}
2668
chaviwfd6d3512019-03-25 13:23:49 -07002669void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002670 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002671 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002672 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2673 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002674 return;
2675 }
2676
Vishnu Nairad321cd2020-08-20 16:40:21 -07002677 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2678 if (focusedToken == token) {
2679 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002680 return;
2681 }
2682
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002683 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2684 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002685 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002686 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687}
2688
2689void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002691 if (ATRACE_ENABLED()) {
2692 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002694 ATRACE_NAME(message.c_str());
2695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002697 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698#endif
2699
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002700 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2701 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002703 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002704 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002705 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706
2707 // Publish the event.
2708 status_t status;
2709 EventEntry* eventEntry = dispatchEntry->eventEntry;
2710 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002711 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002712 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2713 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002716 status =
2717 connection->inputPublisher
2718 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2719 keyEntry->deviceId, keyEntry->source,
2720 keyEntry->displayId, std::move(hmac),
2721 dispatchEntry->resolvedAction,
2722 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2723 keyEntry->scanCode, keyEntry->metaState,
2724 keyEntry->repeatCount, keyEntry->downTime,
2725 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 }
2728
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002729 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 PointerCoords scaledCoords[MAX_POINTERS];
2733 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2734
chaviw82357092020-01-28 13:13:06 -08002735 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2737 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2738 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002739 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2741 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002742 // Don't apply window scale here since we don't want scale to affect raw
2743 // coordinates. The scale will be sent back to the client and applied
2744 // later when requesting relative coordinates.
2745 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2746 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 }
2748 usingCoords = scaledCoords;
2749 }
2750 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 // We don't want the dispatch target to know.
2752 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2753 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2754 scaledCoords[i].clear();
2755 }
2756 usingCoords = scaledCoords;
2757 }
2758 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002759
2760 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761
2762 // Publish the motion event.
2763 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002764 .publishMotionEvent(dispatchEntry->seq,
2765 dispatchEntry->resolvedEventId,
2766 motionEntry->deviceId, motionEntry->source,
2767 motionEntry->displayId, std::move(hmac),
2768 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 motionEntry->actionButton,
2770 dispatchEntry->resolvedFlags,
2771 motionEntry->edgeFlags, motionEntry->metaState,
2772 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002773 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002774 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002775 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 motionEntry->yPrecision,
2777 motionEntry->xCursorPosition,
2778 motionEntry->yCursorPosition,
2779 motionEntry->downTime, motionEntry->eventTime,
2780 motionEntry->pointerCount,
2781 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002782 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 break;
2784 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002785 case EventEntry::Type::FOCUS: {
2786 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2787 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002788 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002789 focusEntry->hasFocus,
2790 mInTouchMode);
2791 break;
2792 }
2793
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002794 case EventEntry::Type::CONFIGURATION_CHANGED:
2795 case EventEntry::Type::DEVICE_RESET: {
2796 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2797 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 }
2801
2802 // Check the result.
2803 if (status) {
2804 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002805 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 "This is unexpected because the wait queue is empty, so the pipe "
2808 "should be empty and we shouldn't have any problems writing an "
2809 "event to it, status=%d",
2810 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2812 } else {
2813 // Pipe is full and we are waiting for the app to finish process some events
2814 // before sending more events to it.
2815#if DEBUG_DISPATCH_CYCLE
2816 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 "waiting for the application to catch up",
2818 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821 } else {
2822 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 "status=%d",
2824 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2826 }
2827 return;
2828 }
2829
2830 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002831 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2832 connection->outboundQueue.end(),
2833 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002834 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002835 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002836 if (connection->responsive) {
2837 mAnrTracker.insert(dispatchEntry->timeoutTime,
2838 connection->inputChannel->getConnectionToken());
2839 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002840 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 }
2842}
2843
chaviw09c8d2d2020-08-24 15:48:26 -07002844std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2845 size_t size;
2846 switch (event.type) {
2847 case VerifiedInputEvent::Type::KEY: {
2848 size = sizeof(VerifiedKeyEvent);
2849 break;
2850 }
2851 case VerifiedInputEvent::Type::MOTION: {
2852 size = sizeof(VerifiedMotionEvent);
2853 break;
2854 }
2855 }
2856 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2857 return mHmacKeyManager.sign(start, size);
2858}
2859
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002860const std::array<uint8_t, 32> InputDispatcher::getSignature(
2861 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2862 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2863 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2864 // Only sign events up and down events as the purely move events
2865 // are tied to their up/down counterparts so signing would be redundant.
2866 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2867 verifiedEvent.actionMasked = actionMasked;
2868 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002869 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002870 }
2871 return INVALID_HMAC;
2872}
2873
2874const std::array<uint8_t, 32> InputDispatcher::getSignature(
2875 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2876 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2877 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2878 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002879 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002880}
2881
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 const sp<Connection>& connection, uint32_t seq,
2884 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885#if DEBUG_DISPATCH_CYCLE
2886 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#endif
2889
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 if (connection->status == Connection::STATUS_BROKEN ||
2891 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 return;
2893 }
2894
2895 // Notify other system components and prepare to start the next dispatch cycle.
2896 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2897}
2898
2899void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 const sp<Connection>& connection,
2901 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902#if DEBUG_DISPATCH_CYCLE
2903 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905#endif
2906
2907 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002908 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002909 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002910 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002911 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
2913 // The connection appears to be unrecoverably broken.
2914 // Ignore already broken or zombie connections.
2915 if (connection->status == Connection::STATUS_NORMAL) {
2916 connection->status = Connection::STATUS_BROKEN;
2917
2918 if (notify) {
2919 // Notify other system components.
2920 onDispatchCycleBrokenLocked(currentTime, connection);
2921 }
2922 }
2923}
2924
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002925void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2926 while (!queue.empty()) {
2927 DispatchEntry* dispatchEntry = queue.front();
2928 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002929 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
2931}
2932
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002933void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002935 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 }
2937 delete dispatchEntry;
2938}
2939
2940int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2941 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2942
2943 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002944 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002946 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 "fd=%d, events=0x%x",
2949 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 return 0; // remove the callback
2951 }
2952
2953 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002954 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2956 if (!(events & ALOOPER_EVENT_INPUT)) {
2957 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 "events=0x%x",
2959 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 return 1;
2961 }
2962
2963 nsecs_t currentTime = now();
2964 bool gotOne = false;
2965 status_t status;
2966 for (;;) {
2967 uint32_t seq;
2968 bool handled;
2969 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2970 if (status) {
2971 break;
2972 }
2973 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2974 gotOne = true;
2975 }
2976 if (gotOne) {
2977 d->runCommandsLockedInterruptible();
2978 if (status == WOULD_BLOCK) {
2979 return 1;
2980 }
2981 }
2982
2983 notify = status != DEAD_OBJECT || !connection->monitor;
2984 if (notify) {
2985 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 }
2988 } else {
2989 // Monitor channels are never explicitly unregistered.
2990 // We do it automatically when the remote endpoint is closed so don't warn
2991 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002992 const bool stillHaveWindowHandle =
2993 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2994 nullptr;
2995 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 if (notify) {
2997 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 "events=0x%x",
2999 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 }
3001 }
3002
Garfield Tan15601662020-09-22 15:32:38 -07003003 // Remove the channel.
3004 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007}
3008
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003011 for (const auto& pair : mConnectionsByFd) {
3012 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 }
3014}
3015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003017 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003018 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3019 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3020}
3021
3022void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3023 const CancelationOptions& options,
3024 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3025 for (const auto& it : monitorsByDisplay) {
3026 const std::vector<Monitor>& monitors = it.second;
3027 for (const Monitor& monitor : monitors) {
3028 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003029 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003030 }
3031}
3032
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003034 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003035 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003036 if (connection == nullptr) {
3037 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003039
3040 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041}
3042
3043void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3044 const sp<Connection>& connection, const CancelationOptions& options) {
3045 if (connection->status == Connection::STATUS_BROKEN) {
3046 return;
3047 }
3048
3049 nsecs_t currentTime = now();
3050
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003051 std::vector<EventEntry*> cancelationEvents =
3052 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003054 if (cancelationEvents.empty()) {
3055 return;
3056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003058 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3059 "with reality: %s, mode=%d.",
3060 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3061 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003063
3064 InputTarget target;
3065 sp<InputWindowHandle> windowHandle =
3066 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3067 if (windowHandle != nullptr) {
3068 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003069 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003070 target.globalScaleFactor = windowInfo->globalScaleFactor;
3071 }
3072 target.inputChannel = connection->inputChannel;
3073 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3074
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003075 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3076 EventEntry* cancelationEventEntry = cancelationEvents[i];
3077 switch (cancelationEventEntry->type) {
3078 case EventEntry::Type::KEY: {
3079 logOutboundKeyDetails("cancel - ",
3080 static_cast<const KeyEntry&>(*cancelationEventEntry));
3081 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003083 case EventEntry::Type::MOTION: {
3084 logOutboundMotionDetails("cancel - ",
3085 static_cast<const MotionEntry&>(*cancelationEventEntry));
3086 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003088 case EventEntry::Type::FOCUS: {
3089 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3090 break;
3091 }
3092 case EventEntry::Type::CONFIGURATION_CHANGED:
3093 case EventEntry::Type::DEVICE_RESET: {
3094 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3095 EventEntry::typeToString(cancelationEventEntry->type));
3096 break;
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 }
3099
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003100 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3101 target, InputTarget::FLAG_DISPATCH_AS_IS);
3102
3103 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003105
3106 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107}
3108
Svet Ganov5d3bc372020-01-26 23:11:07 -08003109void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3110 const sp<Connection>& connection) {
3111 if (connection->status == Connection::STATUS_BROKEN) {
3112 return;
3113 }
3114
3115 nsecs_t currentTime = now();
3116
3117 std::vector<EventEntry*> downEvents =
3118 connection->inputState.synthesizePointerDownEvents(currentTime);
3119
3120 if (downEvents.empty()) {
3121 return;
3122 }
3123
3124#if DEBUG_OUTBOUND_EVENT_DETAILS
3125 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3126 connection->getInputChannelName().c_str(), downEvents.size());
3127#endif
3128
3129 InputTarget target;
3130 sp<InputWindowHandle> windowHandle =
3131 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3132 if (windowHandle != nullptr) {
3133 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003134 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003135 target.globalScaleFactor = windowInfo->globalScaleFactor;
3136 }
3137 target.inputChannel = connection->inputChannel;
3138 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3139
3140 for (EventEntry* downEventEntry : downEvents) {
3141 switch (downEventEntry->type) {
3142 case EventEntry::Type::MOTION: {
3143 logOutboundMotionDetails("down - ",
3144 static_cast<const MotionEntry&>(*downEventEntry));
3145 break;
3146 }
3147
3148 case EventEntry::Type::KEY:
3149 case EventEntry::Type::FOCUS:
3150 case EventEntry::Type::CONFIGURATION_CHANGED:
3151 case EventEntry::Type::DEVICE_RESET: {
3152 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3153 EventEntry::typeToString(downEventEntry->type));
3154 break;
3155 }
3156 }
3157
3158 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3159 target, InputTarget::FLAG_DISPATCH_AS_IS);
3160
3161 downEventEntry->release();
3162 }
3163
3164 startDispatchCycleLocked(currentTime, connection);
3165}
3166
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003167MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003168 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 ALOG_ASSERT(pointerIds.value != 0);
3170
3171 uint32_t splitPointerIndexMap[MAX_POINTERS];
3172 PointerProperties splitPointerProperties[MAX_POINTERS];
3173 PointerCoords splitPointerCoords[MAX_POINTERS];
3174
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003175 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 uint32_t splitPointerCount = 0;
3177
3178 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003181 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 uint32_t pointerId = uint32_t(pointerProperties.id);
3183 if (pointerIds.hasBit(pointerId)) {
3184 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3185 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3186 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003187 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 splitPointerCount += 1;
3189 }
3190 }
3191
3192 if (splitPointerCount != pointerIds.count()) {
3193 // This is bad. We are missing some of the pointers that we expected to deliver.
3194 // Most likely this indicates that we received an ACTION_MOVE events that has
3195 // different pointer ids than we expected based on the previous ACTION_DOWN
3196 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3197 // in this way.
3198 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 "we expected there to be %d pointers. This probably means we received "
3200 "a broken sequence of pointer ids from the input device.",
3201 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003202 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003205 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3208 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3210 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003211 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 uint32_t pointerId = uint32_t(pointerProperties.id);
3213 if (pointerIds.hasBit(pointerId)) {
3214 if (pointerIds.count() == 1) {
3215 // The first/last pointer went down/up.
3216 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 ? AMOTION_EVENT_ACTION_DOWN
3218 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 } else {
3220 // A secondary pointer went down/up.
3221 uint32_t splitPointerIndex = 0;
3222 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3223 splitPointerIndex += 1;
3224 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 action = maskedAction |
3226 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228 } else {
3229 // An unrelated pointer changed.
3230 action = AMOTION_EVENT_ACTION_MOVE;
3231 }
3232 }
3233
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003234 int32_t newId = mIdGenerator.nextId();
3235 if (ATRACE_ENABLED()) {
3236 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3237 ") to MotionEvent(id=0x%" PRIx32 ").",
3238 originalMotionEntry.id, newId);
3239 ATRACE_NAME(message.c_str());
3240 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003241 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003242 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3243 originalMotionEntry.source, originalMotionEntry.displayId,
3244 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003245 originalMotionEntry.actionButton, originalMotionEntry.flags,
3246 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3247 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3248 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3249 originalMotionEntry.xCursorPosition,
3250 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003251 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003253 if (originalMotionEntry.injectionState) {
3254 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 splitMotionEntry->injectionState->refCount += 1;
3256 }
3257
3258 return splitMotionEntry;
3259}
3260
3261void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3262#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003263 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264#endif
3265
3266 bool needWake;
3267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003268 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
Prabir Pradhan42611e02018-11-27 14:04:02 -08003270 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003271 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 needWake = enqueueInboundEventLocked(newEntry);
3273 } // release lock
3274
3275 if (needWake) {
3276 mLooper->wake();
3277 }
3278}
3279
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003280/**
3281 * If one of the meta shortcuts is detected, process them here:
3282 * Meta + Backspace -> generate BACK
3283 * Meta + Enter -> generate HOME
3284 * This will potentially overwrite keyCode and metaState.
3285 */
3286void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003288 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3289 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3290 if (keyCode == AKEYCODE_DEL) {
3291 newKeyCode = AKEYCODE_BACK;
3292 } else if (keyCode == AKEYCODE_ENTER) {
3293 newKeyCode = AKEYCODE_HOME;
3294 }
3295 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003296 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003297 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003298 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003299 keyCode = newKeyCode;
3300 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3301 }
3302 } else if (action == AKEY_EVENT_ACTION_UP) {
3303 // In order to maintain a consistent stream of up and down events, check to see if the key
3304 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3305 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003306 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003307 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003308 auto replacementIt = mReplacedKeys.find(replacement);
3309 if (replacementIt != mReplacedKeys.end()) {
3310 keyCode = replacementIt->second;
3311 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003312 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3313 }
3314 }
3315}
3316
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3318#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3320 "policyFlags=0x%x, action=0x%x, "
3321 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3322 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3323 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3324 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#endif
3326 if (!validateKeyEvent(args->action)) {
3327 return;
3328 }
3329
3330 uint32_t policyFlags = args->policyFlags;
3331 int32_t flags = args->flags;
3332 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003333 // InputDispatcher tracks and generates key repeats on behalf of
3334 // whatever notifies it, so repeatCount should always be set to 0
3335 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3337 policyFlags |= POLICY_FLAG_VIRTUAL;
3338 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 if (policyFlags & POLICY_FLAG_FUNCTION) {
3341 metaState |= AMETA_FUNCTION_ON;
3342 }
3343
3344 policyFlags |= POLICY_FLAG_TRUSTED;
3345
Michael Wright78f24442014-08-06 15:55:28 -07003346 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003347 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003348
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003350 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003351 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3352 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Michael Wright2b3c3302018-03-02 17:19:13 +00003354 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003356 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3357 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 bool needWake;
3362 { // acquire lock
3363 mLock.lock();
3364
3365 if (shouldSendKeyToInputFilterLocked(args)) {
3366 mLock.unlock();
3367
3368 policyFlags |= POLICY_FLAG_FILTERED;
3369 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3370 return; // event was consumed by the filter
3371 }
3372
3373 mLock.lock();
3374 }
3375
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003377 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 args->displayId, policyFlags, args->action, flags, keyCode,
3379 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
3381 needWake = enqueueInboundEventLocked(newEntry);
3382 mLock.unlock();
3383 } // release lock
3384
3385 if (needWake) {
3386 mLooper->wake();
3387 }
3388}
3389
3390bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3391 return mInputFilterEnabled;
3392}
3393
3394void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3395#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003396 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3397 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003398 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3399 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003400 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003401 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3402 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3403 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3404 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 for (uint32_t i = 0; i < args->pointerCount; i++) {
3406 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 "x=%f, y=%f, pressure=%f, size=%f, "
3408 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3409 "orientation=%f",
3410 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3411 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3412 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3413 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3414 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3415 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3416 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3417 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3418 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3419 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 }
3421#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3423 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 return;
3425 }
3426
3427 uint32_t policyFlags = args->policyFlags;
3428 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003429
3430 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003431 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003432 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3433 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436
3437 bool needWake;
3438 { // acquire lock
3439 mLock.lock();
3440
3441 if (shouldSendMotionToInputFilterLocked(args)) {
3442 mLock.unlock();
3443
3444 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003445 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003446 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3447 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003448 args->metaState, args->buttonState, args->classification, transform,
3449 args->xPrecision, args->yPrecision, args->xCursorPosition,
3450 args->yCursorPosition, args->downTime, args->eventTime,
3451 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452
3453 policyFlags |= POLICY_FLAG_FILTERED;
3454 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3455 return; // event was consumed by the filter
3456 }
3457
3458 mLock.lock();
3459 }
3460
3461 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003462 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003463 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003464 args->displayId, policyFlags, args->action, args->actionButton,
3465 args->flags, args->metaState, args->buttonState,
3466 args->classification, args->edgeFlags, args->xPrecision,
3467 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3468 args->downTime, args->pointerCount, args->pointerProperties,
3469 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470
3471 needWake = enqueueInboundEventLocked(newEntry);
3472 mLock.unlock();
3473 } // release lock
3474
3475 if (needWake) {
3476 mLooper->wake();
3477 }
3478}
3479
3480bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003481 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482}
3483
3484void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3485#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003486 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487 "switchMask=0x%08x",
3488 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489#endif
3490
3491 uint32_t policyFlags = args->policyFlags;
3492 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003493 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494}
3495
3496void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3497#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3499 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500#endif
3501
3502 bool needWake;
3503 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Prabir Pradhan42611e02018-11-27 14:04:02 -08003506 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003507 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 needWake = enqueueInboundEventLocked(newEntry);
3509 } // release lock
3510
3511 if (needWake) {
3512 mLooper->wake();
3513 }
3514}
3515
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003516InputEventInjectionResult InputDispatcher::injectInputEvent(
3517 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3518 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519#if DEBUG_INBOUND_EVENT_DETAILS
3520 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003521 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3522 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003524 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525
3526 policyFlags |= POLICY_FLAG_INJECTED;
3527 if (hasInjectionPermission(injectorPid, injectorUid)) {
3528 policyFlags |= POLICY_FLAG_TRUSTED;
3529 }
3530
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003531 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003533 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003534 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3535 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003537 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003540 int32_t flags = incomingKey.getFlags();
3541 int32_t keyCode = incomingKey.getKeyCode();
3542 int32_t metaState = incomingKey.getMetaState();
3543 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003544 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003545 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003546 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003547 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3548 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3549 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003551 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3552 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003553 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003554
3555 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3556 android::base::Timer t;
3557 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3558 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3559 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3560 std::to_string(t.duration().count()).c_str());
3561 }
3562 }
3563
3564 mLock.lock();
3565 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003566 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3567 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003568 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3569 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003570 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 injectedEntries.push(injectedEntry);
3572 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 }
3574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575 case AINPUT_EVENT_TYPE_MOTION: {
3576 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3577 int32_t action = motionEvent->getAction();
3578 size_t pointerCount = motionEvent->getPointerCount();
3579 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3580 int32_t actionButton = motionEvent->getActionButton();
3581 int32_t displayId = motionEvent->getDisplayId();
3582 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003583 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003584 }
3585
3586 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3587 nsecs_t eventTime = motionEvent->getEventTime();
3588 android::base::Timer t;
3589 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3590 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3591 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3592 std::to_string(t.duration().count()).c_str());
3593 }
3594 }
3595
3596 mLock.lock();
3597 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3598 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3599 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003600 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3601 motionEvent->getSource(), motionEvent->getDisplayId(),
3602 policyFlags, action, actionButton, motionEvent->getFlags(),
3603 motionEvent->getMetaState(), motionEvent->getButtonState(),
3604 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3605 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003606 motionEvent->getRawXCursorPosition(),
3607 motionEvent->getRawYCursorPosition(),
3608 motionEvent->getDownTime(), uint32_t(pointerCount),
3609 pointerProperties, samplePointerCoords,
3610 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 injectedEntries.push(injectedEntry);
3612 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3613 sampleEventTimes += 1;
3614 samplePointerCoords += pointerCount;
3615 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003616 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003617 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618 motionEvent->getDisplayId(), policyFlags, action,
3619 actionButton, motionEvent->getFlags(),
3620 motionEvent->getMetaState(), motionEvent->getButtonState(),
3621 motionEvent->getClassification(),
3622 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3623 motionEvent->getYPrecision(),
3624 motionEvent->getRawXCursorPosition(),
3625 motionEvent->getRawYCursorPosition(),
3626 motionEvent->getDownTime(), uint32_t(pointerCount),
3627 pointerProperties, samplePointerCoords,
3628 motionEvent->getXOffset(), motionEvent->getYOffset());
3629 injectedEntries.push(nextInjectedEntry);
3630 }
3631 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003634 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003635 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003636 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638
3639 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003640 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 injectionState->injectionIsAsync = true;
3642 }
3643
3644 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003645 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646
3647 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003648 while (!injectedEntries.empty()) {
3649 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3650 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
3652
3653 mLock.unlock();
3654
3655 if (needWake) {
3656 mLooper->wake();
3657 }
3658
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003659 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003661 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003663 if (syncMode == InputEventInjectionSync::NONE) {
3664 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 } else {
3666 for (;;) {
3667 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003668 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 break;
3670 }
3671
3672 nsecs_t remainingTimeout = endTime - now();
3673 if (remainingTimeout <= 0) {
3674#if DEBUG_INJECTION
3675 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003678 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 break;
3680 }
3681
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003682 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003685 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3686 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 while (injectionState->pendingForegroundDispatches != 0) {
3688#if DEBUG_INJECTION
3689 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003690 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691#endif
3692 nsecs_t remainingTimeout = endTime - now();
3693 if (remainingTimeout <= 0) {
3694#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003695 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3696 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003698 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 break;
3700 }
3701
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003702 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704 }
3705 }
3706
3707 injectionState->release();
3708 } // release lock
3709
3710#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003711 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003712 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713#endif
3714
3715 return injectionResult;
3716}
3717
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003718std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003719 std::array<uint8_t, 32> calculatedHmac;
3720 std::unique_ptr<VerifiedInputEvent> result;
3721 switch (event.getType()) {
3722 case AINPUT_EVENT_TYPE_KEY: {
3723 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3724 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3725 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003726 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003727 break;
3728 }
3729 case AINPUT_EVENT_TYPE_MOTION: {
3730 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3731 VerifiedMotionEvent verifiedMotionEvent =
3732 verifiedMotionEventFromMotionEvent(motionEvent);
3733 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003734 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003735 break;
3736 }
3737 default: {
3738 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3739 return nullptr;
3740 }
3741 }
3742 if (calculatedHmac == INVALID_HMAC) {
3743 return nullptr;
3744 }
3745 if (calculatedHmac != event.getHmac()) {
3746 return nullptr;
3747 }
3748 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003749}
3750
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003752 return injectorUid == 0 ||
3753 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754}
3755
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003756void InputDispatcher::setInjectionResult(EventEntry* entry,
3757 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 InjectionState* injectionState = entry->injectionState;
3759 if (injectionState) {
3760#if DEBUG_INJECTION
3761 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003762 "injectorPid=%d, injectorUid=%d",
3763 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764#endif
3765
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003766 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 // Log the outcome since the injector did not wait for the injection result.
3768 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003769 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 ALOGV("Asynchronous input event injection succeeded.");
3771 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003772 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 ALOGW("Asynchronous input event injection failed.");
3774 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003775 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 ALOGW("Asynchronous input event injection permission denied.");
3777 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003778 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 ALOGW("Asynchronous input event injection timed out.");
3780 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003781 case InputEventInjectionResult::PENDING:
3782 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3783 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785 }
3786
3787 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003788 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
3790}
3791
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003792void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 InjectionState* injectionState = entry->injectionState;
3794 if (injectionState) {
3795 injectionState->pendingForegroundDispatches += 1;
3796 }
3797}
3798
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003799void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 InjectionState* injectionState = entry->injectionState;
3801 if (injectionState) {
3802 injectionState->pendingForegroundDispatches -= 1;
3803
3804 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003805 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807 }
3808}
3809
Vishnu Nairad321cd2020-08-20 16:40:21 -07003810const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003811 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003812 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3813 auto it = mWindowHandlesByDisplay.find(displayId);
3814 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003815}
3816
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003818 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003819 if (windowHandleToken == nullptr) {
3820 return nullptr;
3821 }
3822
Arthur Hungb92218b2018-08-14 12:00:21 +08003823 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003824 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003825 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003826 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003827 return windowHandle;
3828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 }
3830 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003831 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832}
3833
Vishnu Nairad321cd2020-08-20 16:40:21 -07003834sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3835 int displayId) const {
3836 if (windowHandleToken == nullptr) {
3837 return nullptr;
3838 }
3839
3840 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3841 if (windowHandle->getToken() == windowHandleToken) {
3842 return windowHandle;
3843 }
3844 }
3845 return nullptr;
3846}
3847
3848sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3849 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3850 return getWindowHandleLocked(focusedToken, displayId);
3851}
3852
Mady Mellor017bcd12020-06-23 19:12:00 +00003853bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3854 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003855 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003856 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003857 if (handle->getId() == windowHandle->getId() &&
3858 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003859 if (windowHandle->getInfo()->displayId != it.first) {
3860 ALOGE("Found window %s in display %" PRId32
3861 ", but it should belong to display %" PRId32,
3862 windowHandle->getName().c_str(), it.first,
3863 windowHandle->getInfo()->displayId);
3864 }
3865 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868 }
3869 return false;
3870}
3871
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003872bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3873 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3874 const bool noInputChannel =
3875 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3876 if (connection != nullptr && noInputChannel) {
3877 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3878 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3879 return false;
3880 }
3881
3882 if (connection == nullptr) {
3883 if (!noInputChannel) {
3884 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3885 }
3886 return false;
3887 }
3888 if (!connection->responsive) {
3889 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3890 return false;
3891 }
3892 return true;
3893}
3894
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003895std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3896 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003897 size_t count = mInputChannelsByToken.count(token);
3898 if (count == 0) {
3899 return nullptr;
3900 }
3901 return mInputChannelsByToken.at(token);
3902}
3903
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003904void InputDispatcher::updateWindowHandlesForDisplayLocked(
3905 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3906 if (inputWindowHandles.empty()) {
3907 // Remove all handles on a display if there are no windows left.
3908 mWindowHandlesByDisplay.erase(displayId);
3909 return;
3910 }
3911
3912 // Since we compare the pointer of input window handles across window updates, we need
3913 // to make sure the handle object for the same window stays unchanged across updates.
3914 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003915 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003916 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003917 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003918 }
3919
3920 std::vector<sp<InputWindowHandle>> newHandles;
3921 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3922 if (!handle->updateInfo()) {
3923 // handle no longer valid
3924 continue;
3925 }
3926
3927 const InputWindowInfo* info = handle->getInfo();
3928 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3929 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3930 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003931 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3932 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3933 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003934 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003935 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003936 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003937 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003938 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003939 }
3940
3941 if (info->displayId != displayId) {
3942 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3943 handle->getName().c_str(), displayId, info->displayId);
3944 continue;
3945 }
3946
Robert Carredd13602020-04-13 17:24:34 -07003947 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3948 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003949 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003950 oldHandle->updateFrom(handle);
3951 newHandles.push_back(oldHandle);
3952 } else {
3953 newHandles.push_back(handle);
3954 }
3955 }
3956
3957 // Insert or replace
3958 mWindowHandlesByDisplay[displayId] = newHandles;
3959}
3960
Arthur Hung72d8dc32020-03-28 00:48:39 +00003961void InputDispatcher::setInputWindows(
3962 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3963 { // acquire lock
3964 std::scoped_lock _l(mLock);
3965 for (auto const& i : handlesPerDisplay) {
3966 setInputWindowsLocked(i.second, i.first);
3967 }
3968 }
3969 // Wake up poll loop since it may need to make new input dispatching choices.
3970 mLooper->wake();
3971}
3972
Arthur Hungb92218b2018-08-14 12:00:21 +08003973/**
3974 * Called from InputManagerService, update window handle list by displayId that can receive input.
3975 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3976 * If set an empty list, remove all handles from the specific display.
3977 * For focused handle, check if need to change and send a cancel event to previous one.
3978 * For removed handle, check if need to send a cancel event if already in touch.
3979 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003980void InputDispatcher::setInputWindowsLocked(
3981 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003982 if (DEBUG_FOCUS) {
3983 std::string windowList;
3984 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3985 windowList += iwh->getName() + " ";
3986 }
3987 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003990 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3991 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3992 const bool noInputWindow =
3993 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3994 if (noInputWindow && window->getToken() != nullptr) {
3995 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3996 window->getName().c_str());
3997 window->releaseChannel();
3998 }
3999 }
4000
Arthur Hung72d8dc32020-03-28 00:48:39 +00004001 // Copy old handles for release if they are no longer present.
4002 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
Arthur Hung72d8dc32020-03-28 00:48:39 +00004004 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004005
Vishnu Nair958da932020-08-21 17:12:37 -07004006 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4007 if (mLastHoverWindowHandle &&
4008 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4009 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004010 mLastHoverWindowHandle = nullptr;
4011 }
4012
Vishnu Nair958da932020-08-21 17:12:37 -07004013 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4014 if (focusedToken) {
4015 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4016 if (result != FocusResult::OK) {
4017 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4018 }
4019 }
4020
4021 std::optional<FocusRequest> focusRequest =
4022 getOptionalValueByKey(mPendingFocusRequests, displayId);
4023 if (focusRequest) {
4024 // If the window from the pending request is now visible, provide it focus.
4025 FocusResult result = handleFocusRequestLocked(*focusRequest);
4026 if (result != FocusResult::NOT_VISIBLE) {
4027 // Drop the request if we were able to change the focus or we cannot change
4028 // it for another reason.
4029 mPendingFocusRequests.erase(displayId);
4030 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004033 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4034 mTouchStatesByDisplay.find(displayId);
4035 if (stateIt != mTouchStatesByDisplay.end()) {
4036 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004037 for (size_t i = 0; i < state.windows.size();) {
4038 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004039 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004040 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004041 ALOGD("Touched window was removed: %s in display %" PRId32,
4042 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004043 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004044 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004045 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4046 if (touchedInputChannel != nullptr) {
4047 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4048 "touched window was removed");
4049 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004051 state.windows.erase(state.windows.begin() + i);
4052 } else {
4053 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
4055 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004056 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004057
Arthur Hung72d8dc32020-03-28 00:48:39 +00004058 // Release information for windows that are no longer present.
4059 // This ensures that unused input channels are released promptly.
4060 // Otherwise, they might stick around until the window handle is destroyed
4061 // which might not happen until the next GC.
4062 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004063 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004064 if (DEBUG_FOCUS) {
4065 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004066 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004067 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004068 }
chaviw291d88a2019-02-14 10:33:58 -08004069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070}
4071
4072void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004073 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004074 if (DEBUG_FOCUS) {
4075 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4076 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4077 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004078 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004079 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Chris Yea209fde2020-07-22 13:54:51 -07004081 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004082 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004083
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004084 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4085 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004086 }
4087
Chris Yea209fde2020-07-22 13:54:51 -07004088 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004089 if (inputApplicationHandle != nullptr) {
4090 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4091 } else {
4092 mFocusedApplicationHandlesByDisplay.erase(displayId);
4093 }
4094
4095 // No matter what the old focused application was, stop waiting on it because it is
4096 // no longer focused.
4097 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 } // release lock
4099
4100 // Wake up poll loop since it may need to make new input dispatching choices.
4101 mLooper->wake();
4102}
4103
Tiger Huang721e26f2018-07-24 22:26:19 +08004104/**
4105 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4106 * the display not specified.
4107 *
4108 * We track any unreleased events for each window. If a window loses the ability to receive the
4109 * released event, we will send a cancel event to it. So when the focused display is changed, we
4110 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4111 * display. The display-specified events won't be affected.
4112 */
4113void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004114 if (DEBUG_FOCUS) {
4115 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4116 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004117 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004118 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004119
4120 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004121 sp<IBinder> oldFocusedWindowToken =
4122 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4123 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004124 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004126 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 CancelationOptions
4128 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4129 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004130 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004131 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4132 }
4133 }
4134 mFocusedDisplayId = displayId;
4135
Chris Ye3c2d6f52020-08-09 10:39:48 -07004136 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004137 sp<IBinder> newFocusedWindowToken =
4138 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4139 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004140
Vishnu Nairad321cd2020-08-20 16:40:21 -07004141 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004142 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004143 if (!mFocusedWindowTokenByDisplay.empty()) {
4144 ALOGE("But another display has a focused window\n%s",
4145 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004146 }
4147 }
4148 }
4149
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004150 if (DEBUG_FOCUS) {
4151 logDispatchStateLocked();
4152 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004153 } // release lock
4154
4155 // Wake up poll loop since it may need to make new input dispatching choices.
4156 mLooper->wake();
4157}
4158
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004160 if (DEBUG_FOCUS) {
4161 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
4164 bool changed;
4165 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004166 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4169 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004170 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172
4173 if (mDispatchEnabled && !enabled) {
4174 resetAndDropEverythingLocked("dispatcher is being disabled");
4175 }
4176
4177 mDispatchEnabled = enabled;
4178 mDispatchFrozen = frozen;
4179 changed = true;
4180 } else {
4181 changed = false;
4182 }
4183
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004184 if (DEBUG_FOCUS) {
4185 logDispatchStateLocked();
4186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 } // release lock
4188
4189 if (changed) {
4190 // Wake up poll loop since it may need to make new input dispatching choices.
4191 mLooper->wake();
4192 }
4193}
4194
4195void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004196 if (DEBUG_FOCUS) {
4197 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
4200 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004201 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202
4203 if (mInputFilterEnabled == enabled) {
4204 return;
4205 }
4206
4207 mInputFilterEnabled = enabled;
4208 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4209 } // release lock
4210
4211 // Wake up poll loop since there might be work to do to drop everything.
4212 mLooper->wake();
4213}
4214
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004215void InputDispatcher::setInTouchMode(bool inTouchMode) {
4216 std::scoped_lock lock(mLock);
4217 mInTouchMode = inTouchMode;
4218}
4219
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004220void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4221 if (opacity < 0 || opacity > 1) {
4222 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4223 return;
4224 }
4225
4226 std::scoped_lock lock(mLock);
4227 mMaximumObscuringOpacityForTouch = opacity;
4228}
4229
4230void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4231 std::scoped_lock lock(mLock);
4232 mBlockUntrustedTouchesMode = mode;
4233}
4234
chaviwfbe5d9c2018-12-26 12:23:37 -08004235bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4236 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004237 if (DEBUG_FOCUS) {
4238 ALOGD("Trivial transfer to same window.");
4239 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004240 return true;
4241 }
4242
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004244 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245
chaviwfbe5d9c2018-12-26 12:23:37 -08004246 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4247 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004248 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004249 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 return false;
4251 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004252 if (DEBUG_FOCUS) {
4253 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4254 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004257 if (DEBUG_FOCUS) {
4258 ALOGD("Cannot transfer focus because windows are on different displays.");
4259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 return false;
4261 }
4262
4263 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004264 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4265 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004266 for (size_t i = 0; i < state.windows.size(); i++) {
4267 const TouchedWindow& touchedWindow = state.windows[i];
4268 if (touchedWindow.windowHandle == fromWindowHandle) {
4269 int32_t oldTargetFlags = touchedWindow.targetFlags;
4270 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004272 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274 int32_t newTargetFlags = oldTargetFlags &
4275 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4276 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004277 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278
Jeff Brownf086ddb2014-02-11 14:28:48 -08004279 found = true;
4280 goto Found;
4281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004287 if (DEBUG_FOCUS) {
4288 ALOGD("Focus transfer failed because from window did not have focus.");
4289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 return false;
4291 }
4292
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004293 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4294 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004295 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004296 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 CancelationOptions
4298 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4299 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004301 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
4303
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004304 if (DEBUG_FOCUS) {
4305 logDispatchStateLocked();
4306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 } // release lock
4308
4309 // Wake up poll loop since it may need to make new input dispatching choices.
4310 mLooper->wake();
4311 return true;
4312}
4313
4314void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004315 if (DEBUG_FOCUS) {
4316 ALOGD("Resetting and dropping all events (%s).", reason);
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
4319 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4320 synthesizeCancelationEventsForAllConnectionsLocked(options);
4321
4322 resetKeyRepeatLocked();
4323 releasePendingEventLocked();
4324 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004325 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004327 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004328 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004330 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331}
4332
4333void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 dumpDispatchStateLocked(dump);
4336
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337 std::istringstream stream(dump);
4338 std::string line;
4339
4340 while (std::getline(stream, line, '\n')) {
4341 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
4343}
4344
Vishnu Nairad321cd2020-08-20 16:40:21 -07004345std::string InputDispatcher::dumpFocusedWindowsLocked() {
4346 if (mFocusedWindowTokenByDisplay.empty()) {
4347 return INDENT "FocusedWindows: <none>\n";
4348 }
4349
4350 std::string dump;
4351 dump += INDENT "FocusedWindows:\n";
4352 for (auto& it : mFocusedWindowTokenByDisplay) {
4353 const int32_t displayId = it.first;
4354 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4355 if (windowHandle) {
4356 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4357 windowHandle->getName().c_str());
4358 } else {
4359 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4360 " has focused token without a window'\n",
4361 displayId);
4362 }
4363 }
4364 return dump;
4365}
4366
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004368 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4369 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4370 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004371 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Tiger Huang721e26f2018-07-24 22:26:19 +08004373 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4374 dump += StringPrintf(INDENT "FocusedApplications:\n");
4375 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4376 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004377 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004378 const std::chrono::duration timeout =
4379 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004381 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004382 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004385 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004387
Vishnu Nairad321cd2020-08-20 16:40:21 -07004388 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004390 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004391 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004392 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4393 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004394 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004395 state.displayId, toString(state.down), toString(state.split),
4396 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004397 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004398 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004399 for (size_t i = 0; i < state.windows.size(); i++) {
4400 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 dump += StringPrintf(INDENT4
4402 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4403 i, touchedWindow.windowHandle->getName().c_str(),
4404 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004405 }
4406 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004407 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004408 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004409 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004410 dump += INDENT3 "Portal windows:\n";
4411 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004412 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4414 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004415 }
4416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004419 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
4421
Arthur Hungb92218b2018-08-14 12:00:21 +08004422 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004424 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004425 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004426 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004427 dump += INDENT2 "Windows:\n";
4428 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004429 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004430 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Arthur Hungb92218b2018-08-14 12:00:21 +08004432 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004433 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4434 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004435 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004437 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004438 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 i, windowInfo->name.c_str(), windowInfo->displayId,
4440 windowInfo->portalToDisplayId,
4441 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004442 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 toString(windowInfo->hasWallpaper),
4444 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004445 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004446 static_cast<int32_t>(windowInfo->type),
4447 windowInfo->frameLeft, windowInfo->frameTop,
4448 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004449 windowInfo->globalScaleFactor,
4450 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004451 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004452 dump += StringPrintf(", inputFeatures=%s",
4453 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004454 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4455 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004456 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004457 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004458 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004459 }
4460 } else {
4461 dump += INDENT2 "Windows: <none>\n";
4462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 }
4464 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004465 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467
Michael Wright3dd60e22019-03-27 22:06:44 +00004468 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004470 const std::vector<Monitor>& monitors = it.second;
4471 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4472 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004473 }
4474 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004475 const std::vector<Monitor>& monitors = it.second;
4476 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4477 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004480 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 }
4482
4483 nsecs_t currentTime = now();
4484
4485 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004486 if (!mRecentQueue.empty()) {
4487 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4488 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004489 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004490 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004491 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
4493 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004494 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496
4497 // Dump event currently being dispatched.
4498 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004499 dump += INDENT "PendingEvent:\n";
4500 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004501 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004502 dump += StringPrintf(", age=%" PRId64 "ms\n",
4503 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004505 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 }
4507
4508 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004509 if (!mInboundQueue.empty()) {
4510 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4511 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004512 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004513 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004517 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004520 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004521 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004522 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4523 const KeyReplacement& replacement = pair.first;
4524 int32_t newKeyCode = pair.second;
4525 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004527 }
4528 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004529 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004530 }
4531
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004532 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004533 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004534 for (const auto& pair : mConnectionsByFd) {
4535 const sp<Connection>& connection = pair.second;
4536 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004538 pair.first, connection->getInputChannelName().c_str(),
4539 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004542 if (!connection->outboundQueue.empty()) {
4543 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4544 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004545 dump += dumpQueue(connection->outboundQueue, currentTime);
4546
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004548 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
4550
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004551 if (!connection->waitQueue.empty()) {
4552 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4553 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004554 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004556 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 }
4559 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004560 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 }
4562
4563 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004564 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4565 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004567 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004570 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004571 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4572 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4573 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574}
4575
Michael Wright3dd60e22019-03-27 22:06:44 +00004576void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4577 const size_t numMonitors = monitors.size();
4578 for (size_t i = 0; i < numMonitors; i++) {
4579 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004580 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004581 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4582 dump += "\n";
4583 }
4584}
4585
Garfield Tan15601662020-09-22 15:32:38 -07004586base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4587 const std::string& name) {
4588#if DEBUG_CHANNEL_CREATION
4589 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590#endif
4591
Garfield Tan15601662020-09-22 15:32:38 -07004592 std::shared_ptr<InputChannel> serverChannel;
4593 std::unique_ptr<InputChannel> clientChannel;
4594 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4595
4596 if (result) {
4597 return base::Error(result) << "Failed to open input channel pair with name " << name;
4598 }
4599
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004601 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004602 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603
Garfield Tan15601662020-09-22 15:32:38 -07004604 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004605 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004606 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4609 } // release lock
4610
4611 // Wake the looper because some connections have changed.
4612 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004613 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614}
4615
Garfield Tan15601662020-09-22 15:32:38 -07004616base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4617 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4618 std::shared_ptr<InputChannel> serverChannel;
4619 std::unique_ptr<InputChannel> clientChannel;
4620 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4621 if (result) {
4622 return base::Error(result) << "Failed to open input channel pair with name " << name;
4623 }
4624
Michael Wright3dd60e22019-03-27 22:06:44 +00004625 { // acquire lock
4626 std::scoped_lock _l(mLock);
4627
4628 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004629 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4630 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004631 }
4632
Garfield Tan15601662020-09-22 15:32:38 -07004633 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004634
Garfield Tan15601662020-09-22 15:32:38 -07004635 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004636 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004637 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004638
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004639 auto& monitorsByDisplay =
4640 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004641 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004642
4643 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004644 }
Garfield Tan15601662020-09-22 15:32:38 -07004645
Michael Wright3dd60e22019-03-27 22:06:44 +00004646 // Wake the looper because some connections have changed.
4647 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004648 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004649}
4650
Garfield Tan15601662020-09-22 15:32:38 -07004651status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004653 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
Garfield Tan15601662020-09-22 15:32:38 -07004655 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 if (status) {
4657 return status;
4658 }
4659 } // release lock
4660
4661 // Wake the poll loop because removing the connection may have changed the current
4662 // synchronization state.
4663 mLooper->wake();
4664 return OK;
4665}
4666
Garfield Tan15601662020-09-22 15:32:38 -07004667status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4668 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004669 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004670 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004671 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 return BAD_VALUE;
4673 }
4674
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004675 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004676 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004677
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004679 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 }
4681
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004682 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
4684 nsecs_t currentTime = now();
4685 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4686
4687 connection->status = Connection::STATUS_ZOMBIE;
4688 return OK;
4689}
4690
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004691void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4692 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4693 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004694}
4695
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004697 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004698 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004699 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004700 std::vector<Monitor>& monitors = it->second;
4701 const size_t numMonitors = monitors.size();
4702 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004703 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004704 monitors.erase(monitors.begin() + i);
4705 break;
4706 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004707 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004708 if (monitors.empty()) {
4709 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004710 } else {
4711 ++it;
4712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 }
4714}
4715
Michael Wright3dd60e22019-03-27 22:06:44 +00004716status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4717 { // acquire lock
4718 std::scoped_lock _l(mLock);
4719 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4720
4721 if (!foundDisplayId) {
4722 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4723 return BAD_VALUE;
4724 }
4725 int32_t displayId = foundDisplayId.value();
4726
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004727 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4728 mTouchStatesByDisplay.find(displayId);
4729 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004730 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4731 return BAD_VALUE;
4732 }
4733
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004734 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004735 std::optional<int32_t> foundDeviceId;
4736 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004737 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004738 foundDeviceId = state.deviceId;
4739 }
4740 }
4741 if (!foundDeviceId || !state.down) {
4742 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004744 return BAD_VALUE;
4745 }
4746 int32_t deviceId = foundDeviceId.value();
4747
4748 // Send cancel events to all the input channels we're stealing from.
4749 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004750 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004751 options.deviceId = deviceId;
4752 options.displayId = displayId;
4753 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004754 std::shared_ptr<InputChannel> channel =
4755 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004756 if (channel != nullptr) {
4757 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4758 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004759 }
4760 // Then clear the current touch state so we stop dispatching to them as well.
4761 state.filterNonMonitors();
4762 }
4763 return OK;
4764}
4765
Michael Wright3dd60e22019-03-27 22:06:44 +00004766std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4767 const sp<IBinder>& token) {
4768 for (const auto& it : mGestureMonitorsByDisplay) {
4769 const std::vector<Monitor>& monitors = it.second;
4770 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004771 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004772 return it.first;
4773 }
4774 }
4775 }
4776 return std::nullopt;
4777}
4778
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004779sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004780 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004781 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004782 }
4783
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004784 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004785 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004786 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004787 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
4789 }
Robert Carr4e670e52018-08-15 13:26:12 -07004790
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004791 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792}
4793
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004794void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004796 removeByValue(mConnectionsByFd, connection);
4797}
4798
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4800 const sp<Connection>& connection, uint32_t seq,
4801 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004802 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4803 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 commandEntry->connection = connection;
4805 commandEntry->eventTime = currentTime;
4806 commandEntry->seq = seq;
4807 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004808 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809}
4810
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004811void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4812 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004816 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4817 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004819 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820}
4821
Vishnu Nairad321cd2020-08-20 16:40:21 -07004822void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4823 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004824 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4825 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004826 commandEntry->oldToken = oldToken;
4827 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004828 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004829}
4830
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004831void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4833 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004834 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004836 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 return;
4838 }
4839 /**
4840 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4841 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4842 * has changed. This could cause newer entries to time out before the already dispatched
4843 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4844 * processes the events linearly. So providing information about the oldest entry seems to be
4845 * most useful.
4846 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004847 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4849 std::string reason =
4850 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004851 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852 ns2ms(currentWait),
4853 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004855 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 reason);
4857
4858 std::unique_ptr<CommandEntry> commandEntry =
4859 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4860 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004861 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862 commandEntry->reason = std::move(reason);
4863 postCommandLocked(std::move(commandEntry));
4864}
4865
Chris Yea209fde2020-07-22 13:54:51 -07004866void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4868 application->getName().c_str());
4869
4870 updateLastAnrStateLocked(application, reason);
4871
4872 std::unique_ptr<CommandEntry> commandEntry =
4873 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4874 commandEntry->inputApplicationHandle = application;
4875 commandEntry->inputChannel = nullptr;
4876 commandEntry->reason = std::move(reason);
4877 postCommandLocked(std::move(commandEntry));
4878}
4879
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004880void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4881 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4882 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4883 commandEntry->obscuringPackage = obscuringPackage;
4884 postCommandLocked(std::move(commandEntry));
4885}
4886
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4888 const std::string& reason) {
4889 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4890 updateLastAnrStateLocked(windowLabel, reason);
4891}
4892
Chris Yea209fde2020-07-22 13:54:51 -07004893void InputDispatcher::updateLastAnrStateLocked(
4894 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4896 updateLastAnrStateLocked(windowLabel, reason);
4897}
4898
4899void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4900 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004902 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 struct tm tm;
4904 localtime_r(&t, &tm);
4905 char timestr[64];
4906 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004907 mLastAnrState.clear();
4908 mLastAnrState += INDENT "ANR:\n";
4909 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004910 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4911 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004912 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913}
4914
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004915void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 mLock.unlock();
4917
4918 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4919
4920 mLock.lock();
4921}
4922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004923void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 sp<Connection> connection = commandEntry->connection;
4925
4926 if (connection->status != Connection::STATUS_ZOMBIE) {
4927 mLock.unlock();
4928
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004929 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
4931 mLock.lock();
4932 }
4933}
4934
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004935void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004936 sp<IBinder> oldToken = commandEntry->oldToken;
4937 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004938 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004939 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004940 mLock.lock();
4941}
4942
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004943void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004944 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004945 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 mLock.unlock();
4947
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004948 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004949 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950
4951 mLock.lock();
4952
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004953 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4955 } else {
4956 // stop waking up for events in this connection, it is already not responding
4957 sp<Connection> connection = getConnectionLocked(token);
4958 if (connection == nullptr) {
4959 return;
4960 }
4961 cancelEventsForAnrLocked(connection);
4962 }
4963}
4964
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004965void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
4966 mLock.unlock();
4967
4968 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
4969
4970 mLock.lock();
4971}
4972
Chris Yea209fde2020-07-22 13:54:51 -07004973void InputDispatcher::extendAnrTimeoutsLocked(
4974 const std::shared_ptr<InputApplicationHandle>& application,
4975 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004976 if (connectionToken == nullptr && application != nullptr) {
4977 // The ANR happened because there's no focused window
4978 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4979 mAwaitedFocusedApplication = application;
4980 }
4981
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004982 sp<Connection> connection = getConnectionLocked(connectionToken);
4983 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004984 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985 return;
4986 }
4987
4988 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004989 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004990
4991 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004992 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004993 for (DispatchEntry* entry : connection->waitQueue) {
4994 if (newTimeout >= entry->timeoutTime) {
4995 // Already removed old entries when connection was marked unresponsive
4996 entry->timeoutTime = newTimeout;
4997 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4998 }
4999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000}
5001
5002void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5003 CommandEntry* commandEntry) {
5004 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005005 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
5007 mLock.unlock();
5008
Michael Wright2b3c3302018-03-02 17:19:13 +00005009 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005010 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005011 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005012 : nullptr;
5013 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005014 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5015 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018
5019 mLock.lock();
5020
5021 if (delay < 0) {
5022 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5023 } else if (!delay) {
5024 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5025 } else {
5026 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5027 entry->interceptKeyWakeupTime = now() + delay;
5028 }
5029 entry->release();
5030}
5031
chaviwfd6d3512019-03-25 13:23:49 -07005032void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5033 mLock.unlock();
5034 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5035 mLock.lock();
5036}
5037
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005038/**
5039 * Connection is responsive if it has no events in the waitQueue that are older than the
5040 * current time.
5041 */
5042static bool isConnectionResponsive(const Connection& connection) {
5043 const nsecs_t currentTime = now();
5044 for (const DispatchEntry* entry : connection.waitQueue) {
5045 if (entry->timeoutTime < currentTime) {
5046 return false;
5047 }
5048 }
5049 return true;
5050}
5051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005054 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005056 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057
5058 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005059 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005060 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005061 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005063 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005064 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005065 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005066 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5067 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005068 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005069 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005070
5071 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005072 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005073 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5074 restartEvent =
5075 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005076 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005077 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5078 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5079 handled);
5080 } else {
5081 restartEvent = false;
5082 }
5083
5084 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005085 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005086 // contents of the wait queue to have been drained, so we need to double-check
5087 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005088 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5089 if (dispatchEntryIt != connection->waitQueue.end()) {
5090 dispatchEntry = *dispatchEntryIt;
5091 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005092 mAnrTracker.erase(dispatchEntry->timeoutTime,
5093 connection->inputChannel->getConnectionToken());
5094 if (!connection->responsive) {
5095 connection->responsive = isConnectionResponsive(*connection);
5096 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005097 traceWaitQueueLength(connection);
5098 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005099 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005100 traceOutboundQueueLength(connection);
5101 } else {
5102 releaseDispatchEntry(dispatchEntry);
5103 }
5104 }
5105
5106 // Start the next dispatch cycle for this connection.
5107 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108}
5109
5110bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005111 DispatchEntry* dispatchEntry,
5112 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005113 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005114 if (!handled) {
5115 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005116 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005117 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005118 return false;
5119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005121 // Get the fallback key state.
5122 // Clear it out after dispatching the UP.
5123 int32_t originalKeyCode = keyEntry->keyCode;
5124 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5125 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5126 connection->inputState.removeFallbackKey(originalKeyCode);
5127 }
5128
5129 if (handled || !dispatchEntry->hasForegroundTarget()) {
5130 // If the application handles the original key for which we previously
5131 // generated a fallback or if the window is not a foreground window,
5132 // then cancel the associated fallback key, if any.
5133 if (fallbackKeyCode != -1) {
5134 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005136 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005137 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5138 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5139 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005141 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005142 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143
5144 mLock.unlock();
5145
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005146 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005147 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
5149 mLock.lock();
5150
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005151 // Cancel the fallback key.
5152 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005154 "application handled the original non-fallback key "
5155 "or is no longer a foreground target, "
5156 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 options.keyCode = fallbackKeyCode;
5158 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005160 connection->inputState.removeFallbackKey(originalKeyCode);
5161 }
5162 } else {
5163 // If the application did not handle a non-fallback key, first check
5164 // that we are in a good state to perform unhandled key event processing
5165 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005167 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005169 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005170 "since this is not an initial down. "
5171 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5172 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005174 return false;
5175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005177 // Dispatch the unhandled key to the policy.
5178#if DEBUG_OUTBOUND_EVENT_DETAILS
5179 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005180 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5181 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005182#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005183 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005184
5185 mLock.unlock();
5186
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005187 bool fallback =
5188 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5189 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005190
5191 mLock.lock();
5192
5193 if (connection->status != Connection::STATUS_NORMAL) {
5194 connection->inputState.removeFallbackKey(originalKeyCode);
5195 return false;
5196 }
5197
5198 // Latch the fallback keycode for this key on an initial down.
5199 // The fallback keycode cannot change at any other point in the lifecycle.
5200 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005202 fallbackKeyCode = event.getKeyCode();
5203 } else {
5204 fallbackKeyCode = AKEYCODE_UNKNOWN;
5205 }
5206 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5207 }
5208
5209 ALOG_ASSERT(fallbackKeyCode != -1);
5210
5211 // Cancel the fallback key if the policy decides not to send it anymore.
5212 // We will continue to dispatch the key to the policy but we will no
5213 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005214 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5215 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005216#if DEBUG_OUTBOUND_EVENT_DETAILS
5217 if (fallback) {
5218 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005219 "as a fallback for %d, but on the DOWN it had requested "
5220 "to send %d instead. Fallback canceled.",
5221 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005222 } else {
5223 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 "but on the DOWN it had requested to send %d. "
5225 "Fallback canceled.",
5226 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005227 }
5228#endif
5229
5230 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5231 "canceling fallback, policy no longer desires it");
5232 options.keyCode = fallbackKeyCode;
5233 synthesizeCancelationEventsForConnectionLocked(connection, options);
5234
5235 fallback = false;
5236 fallbackKeyCode = AKEYCODE_UNKNOWN;
5237 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005238 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005239 }
5240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241
5242#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005243 {
5244 std::string msg;
5245 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5246 connection->inputState.getFallbackKeys();
5247 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005250 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005251 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005252 }
5253#endif
5254
5255 if (fallback) {
5256 // Restart the dispatch cycle using the fallback key.
5257 keyEntry->eventTime = event.getEventTime();
5258 keyEntry->deviceId = event.getDeviceId();
5259 keyEntry->source = event.getSource();
5260 keyEntry->displayId = event.getDisplayId();
5261 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5262 keyEntry->keyCode = fallbackKeyCode;
5263 keyEntry->scanCode = event.getScanCode();
5264 keyEntry->metaState = event.getMetaState();
5265 keyEntry->repeatCount = event.getRepeatCount();
5266 keyEntry->downTime = event.getDownTime();
5267 keyEntry->syntheticRepeat = false;
5268
5269#if DEBUG_OUTBOUND_EVENT_DETAILS
5270 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005271 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5272 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005273#endif
5274 return true; // restart the event
5275 } else {
5276#if DEBUG_OUTBOUND_EVENT_DETAILS
5277 ALOGD("Unhandled key event: No fallback key.");
5278#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005279
5280 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005281 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
5283 }
5284 return false;
5285}
5286
5287bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005288 DispatchEntry* dispatchEntry,
5289 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 return false;
5291}
5292
5293void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5294 mLock.unlock();
5295
5296 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5297
5298 mLock.lock();
5299}
5300
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005301KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5302 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005303 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005304 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5305 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005306 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307}
5308
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005309void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5310 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 // TODO Write some statistics about how long we spend waiting.
5312}
5313
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005314/**
5315 * Report the touch event latency to the statsd server.
5316 * Input events are reported for statistics if:
5317 * - This is a touchscreen event
5318 * - InputFilter is not enabled
5319 * - Event is not injected or synthesized
5320 *
5321 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5322 * from getting aggregated with the "old" data.
5323 */
5324void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5325 REQUIRES(mLock) {
5326 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5327 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5328 if (!reportForStatistics) {
5329 return;
5330 }
5331
5332 if (mTouchStatistics.shouldReport()) {
5333 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5334 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5335 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5336 mTouchStatistics.reset();
5337 }
5338 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5339 mTouchStatistics.addValue(latencyMicros);
5340}
5341
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342void InputDispatcher::traceInboundQueueLengthLocked() {
5343 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005344 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346}
5347
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005348void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 if (ATRACE_ENABLED()) {
5350 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005351 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005352 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 }
5354}
5355
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005356void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 if (ATRACE_ENABLED()) {
5358 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005359 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005360 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
5362}
5363
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005364void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005365 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005367 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 dumpDispatchStateLocked(dump);
5369
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005370 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005371 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005372 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 }
5374}
5375
5376void InputDispatcher::monitor() {
5377 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005378 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005380 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381}
5382
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005383/**
5384 * Wake up the dispatcher and wait until it processes all events and commands.
5385 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5386 * this method can be safely called from any thread, as long as you've ensured that
5387 * the work you are interested in completing has already been queued.
5388 */
5389bool InputDispatcher::waitForIdle() {
5390 /**
5391 * Timeout should represent the longest possible time that a device might spend processing
5392 * events and commands.
5393 */
5394 constexpr std::chrono::duration TIMEOUT = 100ms;
5395 std::unique_lock lock(mLock);
5396 mLooper->wake();
5397 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5398 return result == std::cv_status::no_timeout;
5399}
5400
Vishnu Naire798b472020-07-23 13:52:21 -07005401/**
5402 * Sets focus to the window identified by the token. This must be called
5403 * after updating any input window handles.
5404 *
5405 * Params:
5406 * request.token - input channel token used to identify the window that should gain focus.
5407 * request.focusedToken - the token that the caller expects currently to be focused. If the
5408 * specified token does not match the currently focused window, this request will be dropped.
5409 * If the specified focused token matches the currently focused window, the call will succeed.
5410 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5411 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5412 * when requesting the focus change. This determines which request gets
5413 * precedence if there is a focus change request from another source such as pointer down.
5414 */
Vishnu Nair958da932020-08-21 17:12:37 -07005415void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5416 { // acquire lock
5417 std::scoped_lock _l(mLock);
5418
5419 const int32_t displayId = request.displayId;
5420 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5421 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5422 ALOGD_IF(DEBUG_FOCUS,
5423 "setFocusedWindow on display %" PRId32
5424 " ignored, reason: focusedToken is not focused",
5425 displayId);
5426 return;
5427 }
5428
5429 mPendingFocusRequests.erase(displayId);
5430 FocusResult result = handleFocusRequestLocked(request);
5431 if (result == FocusResult::NOT_VISIBLE) {
5432 // The requested window is not currently visible. Wait for the window to become visible
5433 // and then provide it focus. This is to handle situations where a user action triggers
5434 // a new window to appear. We want to be able to queue any key events after the user
5435 // action and deliver it to the newly focused window. In order for this to happen, we
5436 // take focus from the currently focused window so key events can be queued.
5437 ALOGD_IF(DEBUG_FOCUS,
5438 "setFocusedWindow on display %" PRId32
5439 " pending, reason: window is not visible",
5440 displayId);
5441 mPendingFocusRequests[displayId] = request;
5442 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5443 "setFocusedWindow_AwaitingWindowVisibility");
5444 } else if (result != FocusResult::OK) {
5445 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5446 typeToString(result));
5447 }
5448 } // release lock
5449 // Wake up poll loop since it may need to make new input dispatching choices.
5450 mLooper->wake();
5451}
5452
5453InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5454 const FocusRequest& request) {
5455 const int32_t displayId = request.displayId;
5456 const sp<IBinder> newFocusedToken = request.token;
5457 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5458
5459 if (oldFocusedToken == request.token) {
5460 ALOGD_IF(DEBUG_FOCUS,
5461 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5462 displayId);
5463 return FocusResult::OK;
5464 }
5465
5466 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5467 if (result != FocusResult::OK) {
5468 return result;
5469 }
5470
5471 std::string_view reason =
5472 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5473 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5474 return FocusResult::OK;
5475}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005476
Vishnu Nairad321cd2020-08-20 16:40:21 -07005477void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5478 const sp<IBinder>& newFocusedToken, int32_t displayId,
5479 std::string_view reason) {
5480 if (oldFocusedToken) {
5481 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005482 if (focusedInputChannel) {
5483 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5484 "focus left window");
5485 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005486 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005487 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005488 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005489 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005490 if (newFocusedToken) {
5491 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5492 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005493 }
5494
5495 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005496 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005497 }
5498}
Vishnu Nair958da932020-08-21 17:12:37 -07005499
5500/**
5501 * Checks if the window token can be focused on a display. The token can be focused if there is
5502 * at least one window handle that is visible with the same token and all window handles with the
5503 * same token are focusable.
5504 *
5505 * In the case of mirroring, two windows may share the same window token and their visibility
5506 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5507 * we expect the focusability of the windows to match since its hard to reason why one window can
5508 * receive focus events and the other cannot when both are backed by the same input channel.
5509 */
5510InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5511 int32_t displayId) const {
5512 bool allWindowsAreFocusable = true;
5513 bool visibleWindowFound = false;
5514 bool windowFound = false;
5515 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5516 if (window->getToken() != token) {
5517 continue;
5518 }
5519 windowFound = true;
5520 if (window->getInfo()->visible) {
5521 // Check if at least a single window is visible.
5522 visibleWindowFound = true;
5523 }
5524 if (!window->getInfo()->focusable) {
5525 // Check if all windows with the window token are focusable.
5526 allWindowsAreFocusable = false;
5527 break;
5528 }
5529 }
5530
5531 if (!windowFound) {
5532 return FocusResult::NO_WINDOW;
5533 }
5534 if (!allWindowsAreFocusable) {
5535 return FocusResult::NOT_FOCUSABLE;
5536 }
5537 if (!visibleWindowFound) {
5538 return FocusResult::NOT_VISIBLE;
5539 }
5540
5541 return FocusResult::OK;
5542}
Garfield Tane84e6f92019-08-29 17:28:41 -07005543} // namespace android::inputdispatcher