blob: 22e658a36400060be36987c11992331926c5f382 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500220static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
221 constexpr size_t maxEntries = 50; // max events to print
222 constexpr size_t skipBegin = maxEntries / 2;
223 const size_t skipEnd = queue.size() - maxEntries / 2;
224 // skip from maxEntries / 2 ... size() - maxEntries/2
225 // only print from 0 .. skipBegin and then from skipEnd .. size()
226
227 std::string dump;
228 for (size_t i = 0; i < queue.size(); i++) {
229 const DispatchEntry& entry = *queue[i];
230 if (i >= skipBegin && i < skipEnd) {
231 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
232 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
233 continue;
234 }
235 dump.append(INDENT4);
236 dump += entry.eventEntry->getDescription();
237 dump += StringPrintf(", seq=%" PRIu32
238 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
239 entry.seq, entry.targetFlags, entry.resolvedAction,
240 ns2ms(currentTime - entry.eventEntry->eventTime));
241 if (entry.deliveryTime != 0) {
242 // This entry was delivered, so add information on how long we've been waiting
243 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
244 }
245 dump.append("\n");
246 }
247 return dump;
248}
249
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700250/**
251 * Find the entry in std::unordered_map by key, and return it.
252 * If the entry is not found, return a default constructed entry.
253 *
254 * Useful when the entries are vectors, since an empty vector will be returned
255 * if the entry is not found.
256 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
257 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700258template <typename K, typename V>
259static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700260 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700261 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800262}
263
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700264/**
265 * Find the entry in std::unordered_map by value, and remove it.
266 * If more than one entry has the same value, then all matching
267 * key-value pairs will be removed.
268 *
269 * Return true if at least one value has been removed.
270 */
271template <typename K, typename V>
272static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
273 bool removed = false;
274 for (auto it = map.begin(); it != map.end();) {
275 if (it->second == value) {
276 it = map.erase(it);
277 removed = true;
278 } else {
279 it++;
280 }
281 }
282 return removed;
283}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284
Vishnu Nair958da932020-08-21 17:12:37 -0700285/**
286 * Find the entry in std::unordered_map by key and return the value as an optional.
287 */
288template <typename K, typename V>
289static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
290 auto it = map.find(key);
291 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
292}
293
chaviwaf87b3e2019-10-01 16:59:28 -0700294static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
295 if (first == second) {
296 return true;
297 }
298
299 if (first == nullptr || second == nullptr) {
300 return false;
301 }
302
303 return first->getToken() == second->getToken();
304}
305
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800306static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
307 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
308}
309
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
311 EventEntry* eventEntry,
312 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700313 if (inputTarget.useDefaultPointerTransform()) {
314 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 inputTargetFlags, transform,
317 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318 }
319
320 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
321 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
322
323 PointerCoords pointerCoords[motionEntry.pointerCount];
324
325 // Use the first pointer information to normalize all other pointers. This could be any pointer
326 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 // uses the transform for the normalized pointer.
328 const ui::Transform& firstPointerTransform =
329 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
330 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331
332 // Iterate through all pointers in the event to normalize against the first.
333 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
334 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
335 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337
338 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 // First, apply the current pointer's transform to update the coordinates into
340 // window space.
341 pointerCoords[pointerIndex].transform(currTransform);
342 // Next, apply the inverse transform of the normalized coordinates so the
343 // current coordinates are transformed into the normalized coordinate space.
344 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345 }
346
347 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800348 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000349 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
350 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
351 motionEntry.metaState, motionEntry.buttonState,
352 motionEntry.classification, motionEntry.edgeFlags,
353 motionEntry.xPrecision, motionEntry.yPrecision,
354 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
355 motionEntry.downTime, motionEntry.pointerCount,
356 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
357 0 /* yOffset */);
358
359 if (motionEntry.injectionState) {
360 combinedMotionEntry->injectionState = motionEntry.injectionState;
361 combinedMotionEntry->injectionState->refCount += 1;
362 }
363
364 std::unique_ptr<DispatchEntry> dispatchEntry =
365 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700366 inputTargetFlags, firstPointerTransform,
367 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368 combinedMotionEntry->release();
369 return dispatchEntry;
370}
371
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700372static void addGestureMonitors(const std::vector<Monitor>& monitors,
373 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
374 float yOffset = 0) {
375 if (monitors.empty()) {
376 return;
377 }
378 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
379 for (const Monitor& monitor : monitors) {
380 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
381 }
382}
383
Garfield Tan15601662020-09-22 15:32:38 -0700384static status_t openInputChannelPair(const std::string& name,
385 std::shared_ptr<InputChannel>& serverChannel,
386 std::unique_ptr<InputChannel>& clientChannel) {
387 std::unique_ptr<InputChannel> uniqueServerChannel;
388 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
389
390 serverChannel = std::move(uniqueServerChannel);
391 return result;
392}
393
Vishnu Nair958da932020-08-21 17:12:37 -0700394const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
395 switch (result) {
396 case InputDispatcher::FocusResult::OK:
397 return "Ok";
398 case InputDispatcher::FocusResult::NO_WINDOW:
399 return "Window not found";
400 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
401 return "Window not focusable";
402 case InputDispatcher::FocusResult::NOT_VISIBLE:
403 return "Window not visible";
404 }
405}
406
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500407template <typename T>
408static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
409 if (lhs == nullptr && rhs == nullptr) {
410 return true;
411 }
412 if (lhs == nullptr || rhs == nullptr) {
413 return false;
414 }
415 return *lhs == *rhs;
416}
417
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418// --- InputDispatcher ---
419
Garfield Tan00f511d2019-06-12 16:55:40 -0700420InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
421 : mPolicy(policy),
422 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700423 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800424 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700425 mAppSwitchSawKeyDown(false),
426 mAppSwitchDueTime(LONG_LONG_MAX),
427 mNextUnblockedEvent(nullptr),
428 mDispatchEnabled(false),
429 mDispatchFrozen(false),
430 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800431 // mInTouchMode will be initialized by the WindowManager to the default device config.
432 // To avoid leaking stack in case that call never comes, and for tests,
433 // initialize it here anyways.
434 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100435 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700436 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800438 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439
Yi Kong9b14ac62018-07-17 13:48:38 -0700440 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441
442 policy->getDispatcherConfiguration(&mConfig);
443}
444
445InputDispatcher::~InputDispatcher() {
446 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800447 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 resetKeyRepeatLocked();
450 releasePendingEventLocked();
451 drainInboundQueueLocked();
452 }
453
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700454 while (!mConnectionsByFd.empty()) {
455 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700456 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 }
458}
459
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700460status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700461 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700462 return ALREADY_EXISTS;
463 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700464 mThread = std::make_unique<InputThread>(
465 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
466 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700467}
468
469status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700470 if (mThread && mThread->isCallingThread()) {
471 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700472 return INVALID_OPERATION;
473 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700474 mThread.reset();
475 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700476}
477
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478void InputDispatcher::dispatchOnce() {
479 nsecs_t nextWakeupTime = LONG_LONG_MAX;
480 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800481 std::scoped_lock _l(mLock);
482 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483
484 // Run a dispatch loop if there are no pending commands.
485 // The dispatch loop might enqueue commands to run afterwards.
486 if (!haveCommandsLocked()) {
487 dispatchOnceInnerLocked(&nextWakeupTime);
488 }
489
490 // Run all pending commands if there are any.
491 // If any commands were run then force the next poll to wake up immediately.
492 if (runCommandsLockedInterruptible()) {
493 nextWakeupTime = LONG_LONG_MIN;
494 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800495
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700496 // If we are still waiting for ack on some events,
497 // we might have to wake up earlier to check if an app is anr'ing.
498 const nsecs_t nextAnrCheck = processAnrsLocked();
499 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
500
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800501 // We are about to enter an infinitely long sleep, because we have no commands or
502 // pending or queued events
503 if (nextWakeupTime == LONG_LONG_MAX) {
504 mDispatcherEnteredIdle.notify_all();
505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 } // release lock
507
508 // Wait for callback or timeout or wake. (make sure we round up, not down)
509 nsecs_t currentTime = now();
510 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
511 mLooper->pollOnce(timeoutMillis);
512}
513
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700514/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500515 * Raise ANR if there is no focused window.
516 * Before the ANR is raised, do a final state check:
517 * 1. The currently focused application must be the same one we are waiting for.
518 * 2. Ensure we still don't have a focused window.
519 */
520void InputDispatcher::processNoFocusedWindowAnrLocked() {
521 // Check if the application that we are waiting for is still focused.
522 std::shared_ptr<InputApplicationHandle> focusedApplication =
523 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
524 if (focusedApplication == nullptr ||
525 focusedApplication->getApplicationToken() !=
526 mAwaitedFocusedApplication->getApplicationToken()) {
527 // Unexpected because we should have reset the ANR timer when focused application changed
528 ALOGE("Waited for a focused window, but focused application has already changed to %s",
529 focusedApplication->getName().c_str());
530 return; // The focused application has changed.
531 }
532
533 const sp<InputWindowHandle>& focusedWindowHandle =
534 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
535 if (focusedWindowHandle != nullptr) {
536 return; // We now have a focused window. No need for ANR.
537 }
538 onAnrLocked(mAwaitedFocusedApplication);
539}
540
541/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700542 * Check if any of the connections' wait queues have events that are too old.
543 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
544 * Return the time at which we should wake up next.
545 */
546nsecs_t InputDispatcher::processAnrsLocked() {
547 const nsecs_t currentTime = now();
548 nsecs_t nextAnrCheck = LONG_LONG_MAX;
549 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
550 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
551 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500552 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700553 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500554 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700555 return LONG_LONG_MIN;
556 } else {
557 // Keep waiting
558 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
559 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
560 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
561 }
562 }
563
564 // Check if any connection ANRs are due
565 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
566 if (currentTime < nextAnrCheck) { // most likely scenario
567 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
568 }
569
570 // If we reached here, we have an unresponsive connection.
571 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
572 if (connection == nullptr) {
573 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
574 return nextAnrCheck;
575 }
576 connection->responsive = false;
577 // Stop waking up for this unresponsive connection
578 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500579 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700580 return LONG_LONG_MIN;
581}
582
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500583std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700584 sp<InputWindowHandle> window = getWindowHandleLocked(token);
585 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500586 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700587 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500588 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700589}
590
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
592 nsecs_t currentTime = now();
593
Jeff Browndc5992e2014-04-11 01:27:26 -0700594 // Reset the key repeat timer whenever normal dispatch is suspended while the
595 // device is in a non-interactive state. This is to ensure that we abort a key
596 // repeat if the device is just coming out of sleep.
597 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 resetKeyRepeatLocked();
599 }
600
601 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
602 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100603 if (DEBUG_FOCUS) {
604 ALOGD("Dispatch frozen. Waiting some more.");
605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 return;
607 }
608
609 // Optimize latency of app switches.
610 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
611 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
612 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
613 if (mAppSwitchDueTime < *nextWakeupTime) {
614 *nextWakeupTime = mAppSwitchDueTime;
615 }
616
617 // Ready to start a new event.
618 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700620 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 if (isAppSwitchDue) {
622 // The inbound queue is empty so the app switch key we were waiting
623 // for will never arrive. Stop waiting for it.
624 resetPendingAppSwitchLocked(false);
625 isAppSwitchDue = false;
626 }
627
628 // Synthesize a key repeat if appropriate.
629 if (mKeyRepeatState.lastKeyEntry) {
630 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
631 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
632 } else {
633 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
634 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
635 }
636 }
637 }
638
639 // Nothing to do if there is no pending event.
640 if (!mPendingEvent) {
641 return;
642 }
643 } else {
644 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700645 mPendingEvent = mInboundQueue.front();
646 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 traceInboundQueueLengthLocked();
648 }
649
650 // Poke user activity for this event.
651 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700652 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 }
655
656 // Now we have an event to dispatch.
657 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700658 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700660 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700662 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700664 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
666
667 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700668 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
670
671 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700672 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 ConfigurationChangedEntry* typedEntry =
674 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
675 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700676 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 break;
678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700680 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700681 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
682 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700683 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 break;
685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100687 case EventEntry::Type::FOCUS: {
688 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
689 dispatchFocusLocked(currentTime, typedEntry);
690 done = true;
691 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
692 break;
693 }
694
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700695 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700696 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
697 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700698 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700699 resetPendingAppSwitchLocked(true);
700 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700701 } else if (dropReason == DropReason::NOT_DROPPED) {
702 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 }
704 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700705 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700706 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700707 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700708 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
709 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 }
711 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
712 break;
713 }
714
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700715 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700717 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
718 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700720 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700721 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700722 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700723 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
724 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725 }
726 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 }
730
731 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700732 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700733 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
Michael Wright3a981722015-06-10 15:26:13 +0100735 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736
737 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700738 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 }
740}
741
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700742/**
743 * Return true if the events preceding this incoming motion event should be dropped
744 * Return false otherwise (the default behaviour)
745 */
746bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700747 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700748 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700749
750 // Optimize case where the current application is unresponsive and the user
751 // decides to touch a window in a different application.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the touch into the other window.
754 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700755 int32_t displayId = motionEntry.displayId;
756 int32_t x = static_cast<int32_t>(
757 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
758 int32_t y = static_cast<int32_t>(
759 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
760 sp<InputWindowHandle> touchedWindowHandle =
761 findTouchedWindowAtLocked(displayId, x, y, nullptr);
762 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700763 touchedWindowHandle->getApplicationToken() !=
764 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700765 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700766 ALOGI("Pruning input queue because user touched a different application while waiting "
767 "for %s",
768 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700769 return true;
770 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700771
772 // Alternatively, maybe there's a gesture monitor that could handle this event
773 std::vector<TouchedMonitor> gestureMonitors =
774 findTouchedGestureMonitorsLocked(displayId, {});
775 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
776 sp<Connection> connection =
777 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000778 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700779 // This monitor could take more input. Drop all events preceding this
780 // event, so that gesture monitor could get a chance to receive the stream
781 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
782 "responsive gesture monitor that may handle the event",
783 mAwaitedFocusedApplication->getName().c_str());
784 return true;
785 }
786 }
787 }
788
789 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
790 // yet been processed by some connections, the dispatcher will wait for these motion
791 // events to be processed before dispatching the key event. This is because these motion events
792 // may cause a new window to be launched, which the user might expect to receive focus.
793 // To prevent waiting forever for such events, just send the key to the currently focused window
794 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
795 ALOGD("Received a new pointer down event, stop waiting for events to process and "
796 "just send the pending key event to the focused window.");
797 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700798 }
799 return false;
800}
801
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700803 bool needWake = mInboundQueue.empty();
804 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 traceInboundQueueLengthLocked();
806
807 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700808 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 // Optimize app switch latency.
810 // If the application takes too long to catch up then we drop all events preceding
811 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700812 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700814 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700816 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700821 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 mAppSwitchSawKeyDown = false;
823 needWake = true;
824 }
825 }
826 }
827 break;
828 }
829
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700831 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
832 mNextUnblockedEvent = entry;
833 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100837 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700838 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
839 break;
840 }
841 case EventEntry::Type::CONFIGURATION_CHANGED:
842 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700843 // nothing to do
844 break;
845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 }
847
848 return needWake;
849}
850
851void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
852 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700853 mRecentQueue.push_back(entry);
854 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
855 mRecentQueue.front()->release();
856 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858}
859
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700861 int32_t y, TouchState* touchState,
862 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700864 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
865 LOG_ALWAYS_FATAL(
866 "Must provide a valid touch state if adding portal windows or outside targets");
867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700869 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800870 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 const InputWindowInfo* windowInfo = windowHandle->getInfo();
872 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100873 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
875 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100876 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
877 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
878 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800880 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 if (portalToDisplayId != ADISPLAY_ID_NONE &&
882 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800883 if (addPortalWindows) {
884 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700885 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800886 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700887 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 // Found window.
891 return windowHandle;
892 }
893 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800894
Michael Wright44753b12020-07-08 13:48:11 +0100895 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700896 touchState->addOrUpdateWindow(windowHandle,
897 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
898 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700903 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904}
905
Garfield Tane84e6f92019-08-29 17:28:41 -0700906std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700907 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000908 std::vector<TouchedMonitor> touchedMonitors;
909
910 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
911 addGestureMonitors(monitors, touchedMonitors);
912 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
913 const InputWindowInfo* windowInfo = portalWindow->getInfo();
914 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
916 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000917 }
918 return touchedMonitors;
919}
920
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700921void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 const char* reason;
923 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700924 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700928 reason = "inbound event was dropped because the policy consumed it";
929 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700930 case DropReason::DISABLED:
931 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700932 ALOGI("Dropped event because input dispatch is disabled.");
933 }
934 reason = "inbound event was dropped because input dispatch is disabled";
935 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700936 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 ALOGI("Dropped event because of pending overdue app switch.");
938 reason = "inbound event was dropped because of pending overdue app switch";
939 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700940 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 ALOGI("Dropped event because the current application is not responding and the user "
942 "has started interacting with a different application.");
943 reason = "inbound event was dropped because the current application is not responding "
944 "and the user has started interacting with a different application";
945 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700946 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 ALOGI("Dropped event because it is stale.");
948 reason = "inbound event was dropped because it is stale";
949 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700950 case DropReason::NOT_DROPPED: {
951 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
955
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700956 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700957 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
959 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700962 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700963 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
964 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700965 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
966 synthesizeCancelationEventsForAllConnectionsLocked(options);
967 } else {
968 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
969 synthesizeCancelationEventsForAllConnectionsLocked(options);
970 }
971 break;
972 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100973 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 case EventEntry::Type::CONFIGURATION_CHANGED:
975 case EventEntry::Type::DEVICE_RESET: {
976 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
977 break;
978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980}
981
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800982static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
984 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985}
986
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700987bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
988 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
989 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
990 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991}
992
993bool InputDispatcher::isAppSwitchPendingLocked() {
994 return mAppSwitchDueTime != LONG_LONG_MAX;
995}
996
997void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
998 mAppSwitchDueTime = LONG_LONG_MAX;
999
1000#if DEBUG_APP_SWITCH
1001 if (handled) {
1002 ALOGD("App switch has arrived.");
1003 } else {
1004 ALOGD("App switch was abandoned.");
1005 }
1006#endif
1007}
1008
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001010 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011}
1012
1013bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001014 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 return false;
1016 }
1017
1018 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001019 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001020 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001022 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
1024 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 return true;
1027}
1028
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001029void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1030 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031}
1032
1033void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001034 while (!mInboundQueue.empty()) {
1035 EventEntry* entry = mInboundQueue.front();
1036 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 releaseInboundEventLocked(entry);
1038 }
1039 traceInboundQueueLengthLocked();
1040}
1041
1042void InputDispatcher::releasePendingEventLocked() {
1043 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001045 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047}
1048
1049void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1050 InjectionState* injectionState = entry->injectionState;
1051 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1052#if DEBUG_DISPATCH_CYCLE
1053 ALOGD("Injected inbound event was dropped.");
1054#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001055 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001058 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060 addRecentEventLocked(entry);
1061 entry->release();
1062}
1063
1064void InputDispatcher::resetKeyRepeatLocked() {
1065 if (mKeyRepeatState.lastKeyEntry) {
1066 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001067 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069}
1070
Garfield Tane84e6f92019-08-29 17:28:41 -07001071KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1073
1074 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001075 uint32_t policyFlags = entry->policyFlags &
1076 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 if (entry->refCount == 1) {
1078 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001079 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 entry->eventTime = currentTime;
1081 entry->policyFlags = policyFlags;
1082 entry->repeatCount += 1;
1083 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001085 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001086 entry->displayId, policyFlags, entry->action, entry->flags,
1087 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
1090 mKeyRepeatState.lastKeyEntry = newEntry;
1091 entry->release();
1092
1093 entry = newEntry;
1094 }
1095 entry->syntheticRepeat = true;
1096
1097 // Increment reference count since we keep a reference to the event in
1098 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1099 entry->refCount += 1;
1100
1101 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1102 return entry;
1103}
1104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1106 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001108 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109#endif
1110
1111 // Reset key repeating in case a keyboard device was added or removed or something.
1112 resetKeyRepeatLocked();
1113
1114 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001115 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1116 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001118 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 return true;
1120}
1121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001124 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126#endif
1127
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 options.deviceId = entry->deviceId;
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
1131 return true;
1132}
1133
Vishnu Nairad321cd2020-08-20 16:40:21 -07001134void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001135 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001136 if (mPendingEvent != nullptr) {
1137 // Move the pending event to the front of the queue. This will give the chance
1138 // for the pending event to get dispatched to the newly focused window
1139 mInboundQueue.push_front(mPendingEvent);
1140 mPendingEvent = nullptr;
1141 }
1142
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001143 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001144 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001145
1146 // This event should go to the front of the queue, but behind all other focus events
1147 // Find the last focus event, and insert right after it
1148 std::deque<EventEntry*>::reverse_iterator it =
1149 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1150 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1151
1152 // Maintain the order of focus events. Insert the entry after all other focus events.
1153 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001154}
1155
1156void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001157 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001158 if (channel == nullptr) {
1159 return; // Window has gone away
1160 }
1161 InputTarget target;
1162 target.inputChannel = channel;
1163 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1164 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001165 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1166 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001167 std::string reason = std::string("reason=").append(entry->reason);
1168 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001169 dispatchEventLocked(currentTime, entry, {target});
1170}
1171
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 if (!entry->dispatchInProgress) {
1176 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1177 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1178 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1179 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001180 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 // We have seen two identical key downs in a row which indicates that the device
1182 // driver is automatically generating key repeats itself. We take note of the
1183 // repeat here, but we disable our own next key repeat timer since it is clear that
1184 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001185 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1186 // Make sure we don't get key down from a different device. If a different
1187 // device Id has same key pressed down, the new device Id will replace the
1188 // current one to hold the key repeat with repeat count reset.
1189 // In the future when got a KEY_UP on the device id, drop it and do not
1190 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1192 resetKeyRepeatLocked();
1193 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1194 } else {
1195 // Not a repeat. Save key down state in case we do see a repeat later.
1196 resetKeyRepeatLocked();
1197 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1198 }
1199 mKeyRepeatState.lastKeyEntry = entry;
1200 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001201 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1202 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1203 // The stale device releases the key, reset staleDeviceId.
1204#if DEBUG_INBOUND_EVENT_DETAILS
1205 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1206#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 resetKeyRepeatLocked();
1209 }
1210
1211 if (entry->repeatCount == 1) {
1212 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1213 } else {
1214 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1215 }
1216
1217 entry->dispatchInProgress = true;
1218
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 }
1221
1222 // Handle case where the policy asked us to try again later last time.
1223 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1224 if (currentTime < entry->interceptKeyWakeupTime) {
1225 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1226 *nextWakeupTime = entry->interceptKeyWakeupTime;
1227 }
1228 return false; // wait until next wakeup
1229 }
1230 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1231 entry->interceptKeyWakeupTime = 0;
1232 }
1233
1234 // Give the policy a chance to intercept the key.
1235 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1236 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001237 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001238 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001239 sp<IBinder> focusedWindowToken =
1240 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1241 if (focusedWindowToken != nullptr) {
1242 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001245 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 entry->refCount += 1;
1247 return false; // wait for the command to run
1248 } else {
1249 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1250 }
1251 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001252 if (*dropReason == DropReason::NOT_DROPPED) {
1253 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255 }
1256
1257 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001258 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001260 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001262 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 return true;
1264 }
1265
1266 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001267 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001269 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1271 return false;
1272 }
1273
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001274 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1276 return true;
1277 }
1278
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001279 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001280 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281
1282 // Dispatch the key.
1283 dispatchEventLocked(currentTime, entry, inputTargets);
1284 return true;
1285}
1286
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001289 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1291 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001292 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1293 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1294 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295#endif
1296}
1297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1299 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001300 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001302 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 entry->dispatchInProgress = true;
1304
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001305 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 }
1307
1308 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001309 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001310 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001311 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001312 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 return true;
1314 }
1315
1316 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1317
1318 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001319 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320
1321 bool conflictingPointerActions = false;
1322 int32_t injectionResult;
1323 if (isPointerEvent) {
1324 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 } else {
1329 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001331 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1334 return false;
1335 }
1336
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001337 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001338 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1339 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1340 return true;
1341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001343 CancelationOptions::Mode mode(isPointerEvent
1344 ? CancelationOptions::CANCEL_POINTER_EVENTS
1345 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1346 CancelationOptions options(mode, "input event injection failed");
1347 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 return true;
1349 }
1350
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001351 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001352 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001354 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001355 std::unordered_map<int32_t, TouchState>::iterator it =
1356 mTouchStatesByDisplay.find(entry->displayId);
1357 if (it != mTouchStatesByDisplay.end()) {
1358 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001359 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001360 // The event has gone through these portal windows, so we add monitoring targets of
1361 // the corresponding displays as well.
1362 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001363 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001364 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001366 }
1367 }
1368 }
1369 }
1370
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 // Dispatch the motion.
1372 if (conflictingPointerActions) {
1373 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001374 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 synthesizeCancelationEventsForAllConnectionsLocked(options);
1376 }
1377 dispatchEventLocked(currentTime, entry, inputTargets);
1378 return true;
1379}
1380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001383 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001384 ", policyFlags=0x%x, "
1385 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1386 "metaState=0x%x, buttonState=0x%x,"
1387 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1389 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1390 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 "x=%f, y=%f, pressure=%f, size=%f, "
1395 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1396 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001397 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1398 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1399 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1400 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1401 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1402 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1403 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1404 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1405 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1406 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 }
1408#endif
1409}
1410
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1412 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001413 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414#if DEBUG_DISPATCH_CYCLE
1415 ALOGD("dispatchEventToCurrentInputTargets");
1416#endif
1417
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001418 updateInteractionTokensLocked(*eventEntry, inputTargets);
1419
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1421
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001424 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001425 sp<Connection> connection =
1426 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001427 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001428 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001430 if (DEBUG_FOCUS) {
1431 ALOGD("Dropping event delivery to target with channel '%s' because it "
1432 "is no longer registered with the input dispatcher.",
1433 inputTarget.inputChannel->getName().c_str());
1434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436 }
1437}
1438
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001439void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1440 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1441 // If the policy decides to close the app, we will get a channel removal event via
1442 // unregisterInputChannel, and will clean up the connection that way. We are already not
1443 // sending new pointers to the connection when it blocked, but focused events will continue to
1444 // pile up.
1445 ALOGW("Canceling events for %s because it is unresponsive",
1446 connection->inputChannel->getName().c_str());
1447 if (connection->status == Connection::STATUS_NORMAL) {
1448 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1449 "application not responding");
1450 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
1452}
1453
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001454void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001455 if (DEBUG_FOCUS) {
1456 ALOGD("Resetting ANR timeouts.");
1457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001460 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001461 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462}
1463
Tiger Huang721e26f2018-07-24 22:26:19 +08001464/**
1465 * Get the display id that the given event should go to. If this event specifies a valid display id,
1466 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1467 * Focused display is the display that the user most recently interacted with.
1468 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001470 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001471 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001472 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1474 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 break;
1476 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001477 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1479 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 break;
1481 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001482 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001483 case EventEntry::Type::CONFIGURATION_CHANGED:
1484 case EventEntry::Type::DEVICE_RESET: {
1485 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001486 return ADISPLAY_ID_NONE;
1487 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001488 }
1489 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1490}
1491
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001492bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1493 const char* focusedWindowName) {
1494 if (mAnrTracker.empty()) {
1495 // already processed all events that we waited for
1496 mKeyIsWaitingForEventsTimeout = std::nullopt;
1497 return false;
1498 }
1499
1500 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1501 // Start the timer
1502 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1503 "focus to change",
1504 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001505 mKeyIsWaitingForEventsTimeout = currentTime +
1506 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1507 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001508 return true;
1509 }
1510
1511 // We still have pending events, and already started the timer
1512 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1513 return true; // Still waiting
1514 }
1515
1516 // Waited too long, and some connection still hasn't processed all motions
1517 // Just send the key to the focused window
1518 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1519 focusedWindowName);
1520 mKeyIsWaitingForEventsTimeout = std::nullopt;
1521 return false;
1522}
1523
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001526 std::vector<InputTarget>& inputTargets,
1527 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001528 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529
Tiger Huang721e26f2018-07-24 22:26:19 +08001530 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001531 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001532 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001533 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1534
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 // If there is no currently focused window and no focused application
1536 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001537 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1538 ALOGI("Dropping %s event because there is no focused window or focused application in "
1539 "display %" PRId32 ".",
1540 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001541 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001544 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1545 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1546 // start interacting with another application via touch (app switch). This code can be removed
1547 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1548 // an app is expected to have a focused window.
1549 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1550 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1551 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001552 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1553 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1554 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001555 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001556 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001557 ALOGW("Waiting because no window has focus but %s may eventually add a "
1558 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001559 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001560 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1561 return INPUT_EVENT_INJECTION_PENDING;
1562 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1563 // Already raised ANR. Drop the event
1564 ALOGE("Dropping %s event because there is no focused window",
1565 EventEntry::typeToString(entry.type));
1566 return INPUT_EVENT_INJECTION_FAILED;
1567 } else {
1568 // Still waiting for the focused window
1569 return INPUT_EVENT_INJECTION_PENDING;
1570 }
1571 }
1572
1573 // we have a valid, non-null focused window
1574 resetNoFocusedWindowTimeoutLocked();
1575
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001578 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 }
1580
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001581 if (focusedWindowHandle->getInfo()->paused) {
1582 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1583 return INPUT_EVENT_INJECTION_PENDING;
1584 }
1585
1586 // If the event is a key event, then we must wait for all previous events to
1587 // complete before delivering it because previous events may have the
1588 // side-effect of transferring focus to a different window and we want to
1589 // ensure that the following keys are sent to the new window.
1590 //
1591 // Suppose the user touches a button in a window then immediately presses "A".
1592 // If the button causes a pop-up window to appear then we want to ensure that
1593 // the "A" key is delivered to the new pop-up window. This is because users
1594 // often anticipate pending UI changes when typing on a keyboard.
1595 // To obtain this behavior, we must serialize key events with respect to all
1596 // prior input events.
1597 if (entry.type == EventEntry::Type::KEY) {
1598 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1599 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1600 return INPUT_EVENT_INJECTION_PENDING;
1601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 }
1603
1604 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001605 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1607 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608
1609 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001610 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611}
1612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001613/**
1614 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1615 * that are currently unresponsive.
1616 */
1617std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1618 const std::vector<TouchedMonitor>& monitors) const {
1619 std::vector<TouchedMonitor> responsiveMonitors;
1620 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1621 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1622 sp<Connection> connection = getConnectionLocked(
1623 monitor.monitor.inputChannel->getConnectionToken());
1624 if (connection == nullptr) {
1625 ALOGE("Could not find connection for monitor %s",
1626 monitor.monitor.inputChannel->getName().c_str());
1627 return false;
1628 }
1629 if (!connection->responsive) {
1630 ALOGW("Unresponsive monitor %s will not get the new gesture",
1631 connection->inputChannel->getName().c_str());
1632 return false;
1633 }
1634 return true;
1635 });
1636 return responsiveMonitors;
1637}
1638
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001641 std::vector<InputTarget>& inputTargets,
1642 nsecs_t* nextWakeupTime,
1643 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.
1658 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1659 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.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1694 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.
1709 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1710 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);
1776 // The order of the operands in the 'if' below is important because even if the feature
1777 // is not BLOCK we want isTouchTrustedLocked() to execute in order to log details to
1778 // logcat.
1779 if (!isTouchTrustedLocked(occlusionInfo) &&
1780 mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1781 ALOGW("Dropping untrusted touch event due to %s/%d",
1782 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1783 newTouchedWindowHandle = nullptr;
1784 }
1785 }
1786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 // Also don't send the new touch event to unresponsive gesture monitors
1788 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1789
Michael Wright3dd60e22019-03-27 22:06:44 +00001790 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1791 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 "(%d, %d) in display %" PRId32 ".",
1793 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001794 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1795 goto Failed;
1796 }
1797
1798 if (newTouchedWindowHandle != nullptr) {
1799 // Set target flags.
1800 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1801 if (isSplit) {
1802 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1805 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1806 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1807 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1808 }
1809
1810 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001811 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1812 newHoverWindowHandle = nullptr;
1813 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001814 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 }
1816
1817 // Update the temporary touch state.
1818 BitSet32 pointerIds;
1819 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001820 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001821 pointerIds.markBit(pointerId);
1822 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 } else {
1828 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1829
1830 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001831 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001832 if (DEBUG_FOCUS) {
1833 ALOGD("Dropping event because the pointer is not down or we previously "
1834 "dropped the pointer down event in display %" PRId32,
1835 displayId);
1836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1838 goto Failed;
1839 }
1840
1841 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001842 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001844 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1845 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001848 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001849 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001850 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1851 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001852 if (DEBUG_FOCUS) {
1853 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1854 oldTouchedWindowHandle->getName().c_str(),
1855 newTouchedWindowHandle->getName().c_str(), displayId);
1856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001858 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1859 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1860 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
1862 // Make a slippery entrance into the new window.
1863 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1864 isSplit = true;
1865 }
1866
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 int32_t targetFlags =
1868 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 if (isSplit) {
1870 targetFlags |= InputTarget::FLAG_SPLIT;
1871 }
1872 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1873 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1874 }
1875
1876 BitSet32 pointerIds;
1877 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001878 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001880 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882 }
1883 }
1884
1885 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001886 // Let the previous window know that the hover sequence is over, unless we already did it
1887 // when dispatching it as is to newTouchedWindowHandle.
1888 if (mLastHoverWindowHandle != nullptr &&
1889 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1890 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891#if DEBUG_HOVER
1892 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001895 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1896 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Garfield Tandf26e862020-07-01 20:18:19 -07001899 // Let the new window know that the hover sequence is starting, unless we already did it
1900 // when dispatching it as is to newTouchedWindowHandle.
1901 if (newHoverWindowHandle != nullptr &&
1902 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1903 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904#if DEBUG_HOVER
1905 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001906 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001908 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1909 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1910 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912 }
1913
1914 // Check permission to inject into all touched foreground windows and ensure there
1915 // is at least one touched foreground window.
1916 {
1917 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1920 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001921 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1923 injectionPermission = INJECTION_PERMISSION_DENIED;
1924 goto Failed;
1925 }
1926 }
1927 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001928 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001929 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001930 ALOGI("Dropping event because there is no touched foreground window in display "
1931 "%" PRId32 " or gesture monitor to receive it.",
1932 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1934 goto Failed;
1935 }
1936
1937 // Permission granted to injection into all touched foreground windows.
1938 injectionPermission = INJECTION_PERMISSION_GRANTED;
1939 }
1940
1941 // Check whether windows listening for outside touches are owned by the same UID. If it is
1942 // set the policy flag that we will not reveal coordinate information to this window.
1943 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1944 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001945 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001946 if (foregroundWindowHandle) {
1947 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001948 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001949 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1950 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1951 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1953 InputTarget::FLAG_ZERO_COORDS,
1954 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 }
1957 }
1958 }
1959 }
1960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 // If this is the first pointer going down and the touched window has a wallpaper
1962 // then also add the touched wallpaper windows so they are locked in for the duration
1963 // of the touch gesture.
1964 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1965 // engine only supports touch events. We would need to add a mechanism similar
1966 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1967 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1968 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001969 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001971 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001972 getWindowHandlesLocked(displayId);
1973 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001975 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001976 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001977 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001978 .addOrUpdateWindow(windowHandle,
1979 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1980 InputTarget::
1981 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1982 InputTarget::FLAG_DISPATCH_AS_IS,
1983 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
1985 }
1986 }
1987 }
1988
1989 // Success! Output targets.
1990 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1991
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001994 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 }
1996
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001998 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001999 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 }
2001
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 // Drop the outside or hover touch windows since we will not care about them
2003 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002004 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
2006Failed:
2007 // Check injection permission once and for all.
2008 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 injectionPermission = INJECTION_PERMISSION_GRANTED;
2011 } else {
2012 injectionPermission = INJECTION_PERMISSION_DENIED;
2013 }
2014 }
2015
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002016 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2017 return injectionResult;
2018 }
2019
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002021 if (!wrongDevice) {
2022 if (switchedDevice) {
2023 if (DEBUG_FOCUS) {
2024 ALOGD("Conflicting pointer actions: Switched to a different device.");
2025 }
2026 *outConflictingPointerActions = true;
2027 }
2028
2029 if (isHoverAction) {
2030 // Started hovering, therefore no longer down.
2031 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002032 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002033 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2034 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 *outConflictingPointerActions = true;
2037 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002038 tempTouchState.reset();
2039 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2040 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2041 tempTouchState.deviceId = entry.deviceId;
2042 tempTouchState.source = entry.source;
2043 tempTouchState.displayId = displayId;
2044 }
2045 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2046 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2047 // All pointers up or canceled.
2048 tempTouchState.reset();
2049 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2050 // First pointer went down.
2051 if (oldState && oldState->down) {
2052 if (DEBUG_FOCUS) {
2053 ALOGD("Conflicting pointer actions: Down received while already down.");
2054 }
2055 *outConflictingPointerActions = true;
2056 }
2057 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2058 // One pointer went up.
2059 if (isSplit) {
2060 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2061 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002063 for (size_t i = 0; i < tempTouchState.windows.size();) {
2064 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2065 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2066 touchedWindow.pointerIds.clearBit(pointerId);
2067 if (touchedWindow.pointerIds.isEmpty()) {
2068 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2069 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002072 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002074 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002075 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002076
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002077 // Save changes unless the action was scroll in which case the temporary touch
2078 // state was only valid for this one action.
2079 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2080 if (tempTouchState.displayId >= 0) {
2081 mTouchStatesByDisplay[displayId] = tempTouchState;
2082 } else {
2083 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002087 // Update hover state.
2088 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 return injectionResult;
2092}
2093
2094void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 int32_t targetFlags, BitSet32 pointerIds,
2096 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002097 std::vector<InputTarget>::iterator it =
2098 std::find_if(inputTargets.begin(), inputTargets.end(),
2099 [&windowHandle](const InputTarget& inputTarget) {
2100 return inputTarget.inputChannel->getConnectionToken() ==
2101 windowHandle->getToken();
2102 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002103
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002104 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002105
2106 if (it == inputTargets.end()) {
2107 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002108 std::shared_ptr<InputChannel> inputChannel =
2109 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002110 if (inputChannel == nullptr) {
2111 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2112 return;
2113 }
2114 inputTarget.inputChannel = inputChannel;
2115 inputTarget.flags = targetFlags;
2116 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2117 inputTargets.push_back(inputTarget);
2118 it = inputTargets.end() - 1;
2119 }
2120
2121 ALOG_ASSERT(it->flags == targetFlags);
2122 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2123
chaviw1ff3d1e2020-07-01 15:53:47 -07002124 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125}
2126
Michael Wright3dd60e22019-03-27 22:06:44 +00002127void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002128 int32_t displayId, float xOffset,
2129 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2131 mGlobalMonitorsByDisplay.find(displayId);
2132
2133 if (it != mGlobalMonitorsByDisplay.end()) {
2134 const std::vector<Monitor>& monitors = it->second;
2135 for (const Monitor& monitor : monitors) {
2136 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139}
2140
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2142 float yOffset,
2143 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 InputTarget target;
2145 target.inputChannel = monitor.inputChannel;
2146 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002147 ui::Transform t;
2148 t.set(xOffset, yOffset);
2149 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 inputTargets.push_back(target);
2151}
2152
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 const InjectionState* injectionState) {
2155 if (injectionState &&
2156 (windowHandle == nullptr ||
2157 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2158 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002159 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002161 "owned by uid %d",
2162 injectionState->injectorPid, injectionState->injectorUid,
2163 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 } else {
2165 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
2168 return false;
2169 }
2170 return true;
2171}
2172
Robert Carrc9bf1d32020-04-13 17:21:08 -07002173/**
2174 * Indicate whether one window handle should be considered as obscuring
2175 * another window handle. We only check a few preconditions. Actually
2176 * checking the bounds is left to the caller.
2177 */
2178static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2179 const sp<InputWindowHandle>& otherHandle) {
2180 // Compare by token so cloned layers aren't counted
2181 if (haveSameToken(windowHandle, otherHandle)) {
2182 return false;
2183 }
2184 auto info = windowHandle->getInfo();
2185 auto otherInfo = otherHandle->getInfo();
2186 if (!otherInfo->visible) {
2187 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002188 } else if (info->ownerUid == otherInfo->ownerUid) {
2189 // If ownerUid is the same we don't generate occlusion events as there
2190 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002191 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002192 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002193 return false;
2194 } else if (otherInfo->displayId != info->displayId) {
2195 return false;
2196 }
2197 return true;
2198}
2199
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002200/**
2201 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2202 * untrusted, one should check:
2203 *
2204 * 1. If result.hasBlockingOcclusion is true.
2205 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2206 * BLOCK_UNTRUSTED.
2207 *
2208 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2209 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2210 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2211 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2212 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2213 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2214 *
2215 * If neither of those is true, then it means the touch can be allowed.
2216 */
2217InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2218 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2219 int32_t displayId = windowHandle->getInfo()->displayId;
2220 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2221 TouchOcclusionInfo info;
2222 info.hasBlockingOcclusion = false;
2223 info.obscuringOpacity = 0;
2224 info.obscuringUid = -1;
2225 std::map<int32_t, float> opacityByUid;
2226 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2227 if (windowHandle == otherHandle) {
2228 break; // All future windows are below us. Exit early.
2229 }
2230 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2231 if (canBeObscuredBy(windowHandle, otherHandle) &&
2232 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2233 otherInfo->frameContainsPoint(x, y)) {
2234 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2235 // we perform the checks below to see if the touch can be propagated or not based on the
2236 // window's touch occlusion mode
2237 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2238 info.hasBlockingOcclusion = true;
2239 info.obscuringUid = otherInfo->ownerUid;
2240 info.obscuringPackage = otherInfo->packageName;
2241 break;
2242 }
2243 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2244 uint32_t uid = otherInfo->ownerUid;
2245 float opacity =
2246 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2247 // Given windows A and B:
2248 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2249 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2250 opacityByUid[uid] = opacity;
2251 if (opacity > info.obscuringOpacity) {
2252 info.obscuringOpacity = opacity;
2253 info.obscuringUid = uid;
2254 info.obscuringPackage = otherInfo->packageName;
2255 }
2256 }
2257 }
2258 }
2259 return info;
2260}
2261
2262bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2263 if (occlusionInfo.hasBlockingOcclusion) {
2264 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2265 occlusionInfo.obscuringUid);
2266 return false;
2267 }
2268 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2269 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2270 "%.2f, maximum allowed = %.2f)",
2271 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2272 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2273 return false;
2274 }
2275 return true;
2276}
2277
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2279 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002281 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002282 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002283 if (windowHandle == otherHandle) {
2284 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002287 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002288 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 return true;
2290 }
2291 }
2292 return false;
2293}
2294
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002295bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2296 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002297 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002298 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002299 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002300 if (windowHandle == otherHandle) {
2301 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002302 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002303 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002304 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002305 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002306 return true;
2307 }
2308 }
2309 return false;
2310}
2311
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002312std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002313 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002315 if (applicationHandle != nullptr) {
2316 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002317 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 } else {
2319 return applicationHandle->getName();
2320 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002321 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002322 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002324 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326}
2327
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002329 if (eventEntry.type == EventEntry::Type::FOCUS) {
2330 // Focus events are passed to apps, but do not represent user activity.
2331 return;
2332 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002333 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002334 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002335 if (focusedWindowHandle != nullptr) {
2336 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002337 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002339 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340#endif
2341 return;
2342 }
2343 }
2344
2345 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002346 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002347 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2349 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 return;
2351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002353 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 eventType = USER_ACTIVITY_EVENT_TOUCH;
2355 }
2356 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002358 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2360 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 return;
2362 }
2363 eventType = USER_ACTIVITY_EVENT_BUTTON;
2364 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002366 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002367 case EventEntry::Type::CONFIGURATION_CHANGED:
2368 case EventEntry::Type::DEVICE_RESET: {
2369 LOG_ALWAYS_FATAL("%s events are not user activity",
2370 EventEntry::typeToString(eventEntry.type));
2371 break;
2372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002375 std::unique_ptr<CommandEntry> commandEntry =
2376 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002377 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002379 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380}
2381
2382void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 const sp<Connection>& connection,
2384 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002385 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002386 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002388 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002389 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002390 ATRACE_NAME(message.c_str());
2391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
2393 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002394 "globalScaleFactor=%f, pointerIds=0x%x %s",
2395 connection->getInputChannelName().c_str(), inputTarget.flags,
2396 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2397 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398#endif
2399
2400 // Skip this event if the connection status is not normal.
2401 // We don't want to enqueue additional outbound events if the connection is broken.
2402 if (connection->status != Connection::STATUS_NORMAL) {
2403#if DEBUG_DISPATCH_CYCLE
2404 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002405 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406#endif
2407 return;
2408 }
2409
2410 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002411 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2412 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2413 "Entry type %s should not have FLAG_SPLIT",
2414 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002416 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002417 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002418 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002419 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 if (!splitMotionEntry) {
2421 return; // split event was dropped
2422 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002423 if (DEBUG_FOCUS) {
2424 ALOGD("channel '%s' ~ Split motion event.",
2425 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002426 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 splitMotionEntry->release();
2430 return;
2431 }
2432 }
2433
2434 // Not splitting. Enqueue dispatch entries for the event as is.
2435 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2436}
2437
2438void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002439 const sp<Connection>& connection,
2440 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002441 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002442 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002443 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002444 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002445 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 ATRACE_NAME(message.c_str());
2447 }
2448
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002449 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450
2451 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002452 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002453 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002454 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002456 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002458 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002460 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002462 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464
2465 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002466 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 startDispatchCycleLocked(currentTime, connection);
2468 }
2469}
2470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2472 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002473 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002475 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2477 connection->getInputChannelName().c_str(),
2478 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002479 ATRACE_NAME(message.c_str());
2480 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002481 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 if (!(inputTargetFlags & dispatchMode)) {
2483 return;
2484 }
2485 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2486
2487 // This is a new event.
2488 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002489 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002490 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002492 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2493 // different EventEntry than what was passed in.
2494 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002496 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002497 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002498 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002499 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002500 dispatchEntry->resolvedAction = keyEntry.action;
2501 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2504 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2507 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 return; // skip the inconsistent event
2510 }
2511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002514 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002515 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002516 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2517 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2518 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2519 static_cast<int32_t>(IdGenerator::Source::OTHER);
2520 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002521 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2522 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2523 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2524 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2525 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2526 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2527 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2528 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2529 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2530 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2531 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002533 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 }
2535 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002536 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2537 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2540 "event",
2541 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002546 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2548 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2549 }
2550 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2551 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2555 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2558 "event",
2559 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 return; // skip the inconsistent event
2562 }
2563
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002564 dispatchEntry->resolvedEventId =
2565 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2566 ? mIdGenerator.nextId()
2567 : motionEntry.id;
2568 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2569 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2570 ") to MotionEvent(id=0x%" PRIx32 ").",
2571 motionEntry.id, dispatchEntry->resolvedEventId);
2572 ATRACE_NAME(message.c_str());
2573 }
2574
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002575 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002576 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577
2578 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002580 case EventEntry::Type::FOCUS: {
2581 break;
2582 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002583 case EventEntry::Type::CONFIGURATION_CHANGED:
2584 case EventEntry::Type::DEVICE_RESET: {
2585 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002586 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002587 break;
2588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590
2591 // Remember that we are waiting for this dispatch to complete.
2592 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002593 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 }
2595
2596 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002597 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002598 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002599}
2600
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002601/**
2602 * This function is purely for debugging. It helps us understand where the user interaction
2603 * was taking place. For example, if user is touching launcher, we will see a log that user
2604 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2605 * We will see both launcher and wallpaper in that list.
2606 * Once the interaction with a particular set of connections starts, no new logs will be printed
2607 * until the set of interacted connections changes.
2608 *
2609 * The following items are skipped, to reduce the logspam:
2610 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2611 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2612 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2613 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2614 * Both of those ACTION_UP events would not be logged
2615 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2616 * will not be logged. This is omitted to reduce the amount of data printed.
2617 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2618 * gesture monitor is the only connection receiving the remainder of the gesture.
2619 */
2620void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2621 const std::vector<InputTarget>& targets) {
2622 // Skip ACTION_UP events, and all events other than keys and motions
2623 if (entry.type == EventEntry::Type::KEY) {
2624 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2625 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2626 return;
2627 }
2628 } else if (entry.type == EventEntry::Type::MOTION) {
2629 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2630 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2631 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2632 return;
2633 }
2634 } else {
2635 return; // Not a key or a motion
2636 }
2637
2638 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2639 std::vector<sp<Connection>> newConnections;
2640 for (const InputTarget& target : targets) {
2641 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2642 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2643 continue; // Skip windows that receive ACTION_OUTSIDE
2644 }
2645
2646 sp<IBinder> token = target.inputChannel->getConnectionToken();
2647 sp<Connection> connection = getConnectionLocked(token);
2648 if (connection == nullptr || connection->monitor) {
2649 continue; // We only need to keep track of the non-monitor connections.
2650 }
2651 newConnectionTokens.insert(std::move(token));
2652 newConnections.emplace_back(connection);
2653 }
2654 if (newConnectionTokens == mInteractionConnectionTokens) {
2655 return; // no change
2656 }
2657 mInteractionConnectionTokens = newConnectionTokens;
2658
2659 std::string windowList;
2660 for (const sp<Connection>& connection : newConnections) {
2661 windowList += connection->getWindowName() + ", ";
2662 }
2663 std::string message = "Interaction with windows: " + windowList;
2664 if (windowList.empty()) {
2665 message += "<none>";
2666 }
2667 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2668}
2669
chaviwfd6d3512019-03-25 13:23:49 -07002670void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002671 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002672 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002673 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2674 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002675 return;
2676 }
2677
Vishnu Nairad321cd2020-08-20 16:40:21 -07002678 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2679 if (focusedToken == token) {
2680 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002681 return;
2682 }
2683
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002684 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2685 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002686 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002687 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688}
2689
2690void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002692 if (ATRACE_ENABLED()) {
2693 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002695 ATRACE_NAME(message.c_str());
2696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002698 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699#endif
2700
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002701 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2702 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002704 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002705 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002706 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707
2708 // Publish the event.
2709 status_t status;
2710 EventEntry* eventEntry = dispatchEntry->eventEntry;
2711 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002712 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002713 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2714 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002716 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002717 status =
2718 connection->inputPublisher
2719 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2720 keyEntry->deviceId, keyEntry->source,
2721 keyEntry->displayId, std::move(hmac),
2722 dispatchEntry->resolvedAction,
2723 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2724 keyEntry->scanCode, keyEntry->metaState,
2725 keyEntry->repeatCount, keyEntry->downTime,
2726 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
2729
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002730 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 PointerCoords scaledCoords[MAX_POINTERS];
2734 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2735
chaviw82357092020-01-28 13:13:06 -08002736 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2738 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2739 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002740 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2742 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002743 // Don't apply window scale here since we don't want scale to affect raw
2744 // coordinates. The scale will be sent back to the client and applied
2745 // later when requesting relative coordinates.
2746 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2747 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002748 }
2749 usingCoords = scaledCoords;
2750 }
2751 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 // We don't want the dispatch target to know.
2753 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2754 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2755 scaledCoords[i].clear();
2756 }
2757 usingCoords = scaledCoords;
2758 }
2759 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002760
2761 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762
2763 // Publish the motion event.
2764 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002765 .publishMotionEvent(dispatchEntry->seq,
2766 dispatchEntry->resolvedEventId,
2767 motionEntry->deviceId, motionEntry->source,
2768 motionEntry->displayId, std::move(hmac),
2769 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770 motionEntry->actionButton,
2771 dispatchEntry->resolvedFlags,
2772 motionEntry->edgeFlags, motionEntry->metaState,
2773 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002774 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002775 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002776 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 motionEntry->yPrecision,
2778 motionEntry->xCursorPosition,
2779 motionEntry->yCursorPosition,
2780 motionEntry->downTime, motionEntry->eventTime,
2781 motionEntry->pointerCount,
2782 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002783 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 break;
2785 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002786 case EventEntry::Type::FOCUS: {
2787 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2788 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002789 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002790 focusEntry->hasFocus,
2791 mInTouchMode);
2792 break;
2793 }
2794
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002795 case EventEntry::Type::CONFIGURATION_CHANGED:
2796 case EventEntry::Type::DEVICE_RESET: {
2797 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2798 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002799 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 }
2802
2803 // Check the result.
2804 if (status) {
2805 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002806 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 "This is unexpected because the wait queue is empty, so the pipe "
2809 "should be empty and we shouldn't have any problems writing an "
2810 "event to it, status=%d",
2811 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2813 } else {
2814 // Pipe is full and we are waiting for the app to finish process some events
2815 // before sending more events to it.
2816#if DEBUG_DISPATCH_CYCLE
2817 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 "waiting for the application to catch up",
2819 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
2822 } else {
2823 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 "status=%d",
2825 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2827 }
2828 return;
2829 }
2830
2831 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002832 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2833 connection->outboundQueue.end(),
2834 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002835 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002836 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002837 if (connection->responsive) {
2838 mAnrTracker.insert(dispatchEntry->timeoutTime,
2839 connection->inputChannel->getConnectionToken());
2840 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002841 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
2843}
2844
chaviw09c8d2d2020-08-24 15:48:26 -07002845std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2846 size_t size;
2847 switch (event.type) {
2848 case VerifiedInputEvent::Type::KEY: {
2849 size = sizeof(VerifiedKeyEvent);
2850 break;
2851 }
2852 case VerifiedInputEvent::Type::MOTION: {
2853 size = sizeof(VerifiedMotionEvent);
2854 break;
2855 }
2856 }
2857 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2858 return mHmacKeyManager.sign(start, size);
2859}
2860
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002861const std::array<uint8_t, 32> InputDispatcher::getSignature(
2862 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2863 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2864 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2865 // Only sign events up and down events as the purely move events
2866 // are tied to their up/down counterparts so signing would be redundant.
2867 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2868 verifiedEvent.actionMasked = actionMasked;
2869 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002870 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002871 }
2872 return INVALID_HMAC;
2873}
2874
2875const std::array<uint8_t, 32> InputDispatcher::getSignature(
2876 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2877 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2878 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2879 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002880 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002881}
2882
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 const sp<Connection>& connection, uint32_t seq,
2885 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#if DEBUG_DISPATCH_CYCLE
2887 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889#endif
2890
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 if (connection->status == Connection::STATUS_BROKEN ||
2892 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 return;
2894 }
2895
2896 // Notify other system components and prepare to start the next dispatch cycle.
2897 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2898}
2899
2900void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 const sp<Connection>& connection,
2902 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903#if DEBUG_DISPATCH_CYCLE
2904 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906#endif
2907
2908 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002909 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002910 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002911 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002912 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913
2914 // The connection appears to be unrecoverably broken.
2915 // Ignore already broken or zombie connections.
2916 if (connection->status == Connection::STATUS_NORMAL) {
2917 connection->status = Connection::STATUS_BROKEN;
2918
2919 if (notify) {
2920 // Notify other system components.
2921 onDispatchCycleBrokenLocked(currentTime, connection);
2922 }
2923 }
2924}
2925
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002926void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2927 while (!queue.empty()) {
2928 DispatchEntry* dispatchEntry = queue.front();
2929 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002930 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932}
2933
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002934void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002936 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
2938 delete dispatchEntry;
2939}
2940
2941int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2942 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2943
2944 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002945 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002947 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 "fd=%d, events=0x%x",
2950 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 return 0; // remove the callback
2952 }
2953
2954 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002955 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2957 if (!(events & ALOOPER_EVENT_INPUT)) {
2958 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 "events=0x%x",
2960 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 return 1;
2962 }
2963
2964 nsecs_t currentTime = now();
2965 bool gotOne = false;
2966 status_t status;
2967 for (;;) {
2968 uint32_t seq;
2969 bool handled;
2970 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2971 if (status) {
2972 break;
2973 }
2974 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2975 gotOne = true;
2976 }
2977 if (gotOne) {
2978 d->runCommandsLockedInterruptible();
2979 if (status == WOULD_BLOCK) {
2980 return 1;
2981 }
2982 }
2983
2984 notify = status != DEAD_OBJECT || !connection->monitor;
2985 if (notify) {
2986 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989 } else {
2990 // Monitor channels are never explicitly unregistered.
2991 // We do it automatically when the remote endpoint is closed so don't warn
2992 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002993 const bool stillHaveWindowHandle =
2994 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2995 nullptr;
2996 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 if (notify) {
2998 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 "events=0x%x",
3000 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 }
3002 }
3003
Garfield Tan15601662020-09-22 15:32:38 -07003004 // Remove the channel.
3005 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008}
3009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003012 for (const auto& pair : mConnectionsByFd) {
3013 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
3015}
3016
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003018 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003019 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3020 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3021}
3022
3023void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3024 const CancelationOptions& options,
3025 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3026 for (const auto& it : monitorsByDisplay) {
3027 const std::vector<Monitor>& monitors = it.second;
3028 for (const Monitor& monitor : monitors) {
3029 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003030 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003031 }
3032}
3033
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003035 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003036 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003037 if (connection == nullptr) {
3038 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003040
3041 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042}
3043
3044void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3045 const sp<Connection>& connection, const CancelationOptions& options) {
3046 if (connection->status == Connection::STATUS_BROKEN) {
3047 return;
3048 }
3049
3050 nsecs_t currentTime = now();
3051
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003052 std::vector<EventEntry*> cancelationEvents =
3053 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003055 if (cancelationEvents.empty()) {
3056 return;
3057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003059 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3060 "with reality: %s, mode=%d.",
3061 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3062 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003064
3065 InputTarget target;
3066 sp<InputWindowHandle> windowHandle =
3067 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3068 if (windowHandle != nullptr) {
3069 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003070 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003071 target.globalScaleFactor = windowInfo->globalScaleFactor;
3072 }
3073 target.inputChannel = connection->inputChannel;
3074 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3075
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003076 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3077 EventEntry* cancelationEventEntry = cancelationEvents[i];
3078 switch (cancelationEventEntry->type) {
3079 case EventEntry::Type::KEY: {
3080 logOutboundKeyDetails("cancel - ",
3081 static_cast<const KeyEntry&>(*cancelationEventEntry));
3082 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003084 case EventEntry::Type::MOTION: {
3085 logOutboundMotionDetails("cancel - ",
3086 static_cast<const MotionEntry&>(*cancelationEventEntry));
3087 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003089 case EventEntry::Type::FOCUS: {
3090 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3091 break;
3092 }
3093 case EventEntry::Type::CONFIGURATION_CHANGED:
3094 case EventEntry::Type::DEVICE_RESET: {
3095 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3096 EventEntry::typeToString(cancelationEventEntry->type));
3097 break;
3098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 }
3100
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003101 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3102 target, InputTarget::FLAG_DISPATCH_AS_IS);
3103
3104 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003106
3107 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108}
3109
Svet Ganov5d3bc372020-01-26 23:11:07 -08003110void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3111 const sp<Connection>& connection) {
3112 if (connection->status == Connection::STATUS_BROKEN) {
3113 return;
3114 }
3115
3116 nsecs_t currentTime = now();
3117
3118 std::vector<EventEntry*> downEvents =
3119 connection->inputState.synthesizePointerDownEvents(currentTime);
3120
3121 if (downEvents.empty()) {
3122 return;
3123 }
3124
3125#if DEBUG_OUTBOUND_EVENT_DETAILS
3126 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3127 connection->getInputChannelName().c_str(), downEvents.size());
3128#endif
3129
3130 InputTarget target;
3131 sp<InputWindowHandle> windowHandle =
3132 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3133 if (windowHandle != nullptr) {
3134 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003135 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003136 target.globalScaleFactor = windowInfo->globalScaleFactor;
3137 }
3138 target.inputChannel = connection->inputChannel;
3139 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3140
3141 for (EventEntry* downEventEntry : downEvents) {
3142 switch (downEventEntry->type) {
3143 case EventEntry::Type::MOTION: {
3144 logOutboundMotionDetails("down - ",
3145 static_cast<const MotionEntry&>(*downEventEntry));
3146 break;
3147 }
3148
3149 case EventEntry::Type::KEY:
3150 case EventEntry::Type::FOCUS:
3151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3154 EventEntry::typeToString(downEventEntry->type));
3155 break;
3156 }
3157 }
3158
3159 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3160 target, InputTarget::FLAG_DISPATCH_AS_IS);
3161
3162 downEventEntry->release();
3163 }
3164
3165 startDispatchCycleLocked(currentTime, connection);
3166}
3167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003168MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003169 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 ALOG_ASSERT(pointerIds.value != 0);
3171
3172 uint32_t splitPointerIndexMap[MAX_POINTERS];
3173 PointerProperties splitPointerProperties[MAX_POINTERS];
3174 PointerCoords splitPointerCoords[MAX_POINTERS];
3175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 uint32_t splitPointerCount = 0;
3178
3179 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 uint32_t pointerId = uint32_t(pointerProperties.id);
3184 if (pointerIds.hasBit(pointerId)) {
3185 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3186 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3187 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003188 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 splitPointerCount += 1;
3190 }
3191 }
3192
3193 if (splitPointerCount != pointerIds.count()) {
3194 // This is bad. We are missing some of the pointers that we expected to deliver.
3195 // Most likely this indicates that we received an ACTION_MOVE events that has
3196 // different pointer ids than we expected based on the previous ACTION_DOWN
3197 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3198 // in this way.
3199 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 "we expected there to be %d pointers. This probably means we received "
3201 "a broken sequence of pointer ids from the input device.",
3202 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003203 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3209 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3211 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003212 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 uint32_t pointerId = uint32_t(pointerProperties.id);
3214 if (pointerIds.hasBit(pointerId)) {
3215 if (pointerIds.count() == 1) {
3216 // The first/last pointer went down/up.
3217 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 ? AMOTION_EVENT_ACTION_DOWN
3219 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 } else {
3221 // A secondary pointer went down/up.
3222 uint32_t splitPointerIndex = 0;
3223 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3224 splitPointerIndex += 1;
3225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 action = maskedAction |
3227 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229 } else {
3230 // An unrelated pointer changed.
3231 action = AMOTION_EVENT_ACTION_MOVE;
3232 }
3233 }
3234
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 int32_t newId = mIdGenerator.nextId();
3236 if (ATRACE_ENABLED()) {
3237 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3238 ") to MotionEvent(id=0x%" PRIx32 ").",
3239 originalMotionEntry.id, newId);
3240 ATRACE_NAME(message.c_str());
3241 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003242 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003243 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3244 originalMotionEntry.source, originalMotionEntry.displayId,
3245 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003246 originalMotionEntry.actionButton, originalMotionEntry.flags,
3247 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3248 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3249 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3250 originalMotionEntry.xCursorPosition,
3251 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003252 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003254 if (originalMotionEntry.injectionState) {
3255 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 splitMotionEntry->injectionState->refCount += 1;
3257 }
3258
3259 return splitMotionEntry;
3260}
3261
3262void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3263#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003264 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#endif
3266
3267 bool needWake;
3268 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003269 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Prabir Pradhan42611e02018-11-27 14:04:02 -08003271 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003272 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 needWake = enqueueInboundEventLocked(newEntry);
3274 } // release lock
3275
3276 if (needWake) {
3277 mLooper->wake();
3278 }
3279}
3280
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003281/**
3282 * If one of the meta shortcuts is detected, process them here:
3283 * Meta + Backspace -> generate BACK
3284 * Meta + Enter -> generate HOME
3285 * This will potentially overwrite keyCode and metaState.
3286 */
3287void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003289 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3290 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3291 if (keyCode == AKEYCODE_DEL) {
3292 newKeyCode = AKEYCODE_BACK;
3293 } else if (keyCode == AKEYCODE_ENTER) {
3294 newKeyCode = AKEYCODE_HOME;
3295 }
3296 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003297 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003298 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003299 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003300 keyCode = newKeyCode;
3301 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3302 }
3303 } else if (action == AKEY_EVENT_ACTION_UP) {
3304 // In order to maintain a consistent stream of up and down events, check to see if the key
3305 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3306 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003307 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003308 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003309 auto replacementIt = mReplacedKeys.find(replacement);
3310 if (replacementIt != mReplacedKeys.end()) {
3311 keyCode = replacementIt->second;
3312 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003313 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3314 }
3315 }
3316}
3317
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3319#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3321 "policyFlags=0x%x, action=0x%x, "
3322 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3323 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3324 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3325 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326#endif
3327 if (!validateKeyEvent(args->action)) {
3328 return;
3329 }
3330
3331 uint32_t policyFlags = args->policyFlags;
3332 int32_t flags = args->flags;
3333 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003334 // InputDispatcher tracks and generates key repeats on behalf of
3335 // whatever notifies it, so repeatCount should always be set to 0
3336 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3338 policyFlags |= POLICY_FLAG_VIRTUAL;
3339 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 if (policyFlags & POLICY_FLAG_FUNCTION) {
3342 metaState |= AMETA_FUNCTION_ON;
3343 }
3344
3345 policyFlags |= POLICY_FLAG_TRUSTED;
3346
Michael Wright78f24442014-08-06 15:55:28 -07003347 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003348 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003349
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003351 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003352 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3353 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
Michael Wright2b3c3302018-03-02 17:19:13 +00003355 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003357 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3358 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 bool needWake;
3363 { // acquire lock
3364 mLock.lock();
3365
3366 if (shouldSendKeyToInputFilterLocked(args)) {
3367 mLock.unlock();
3368
3369 policyFlags |= POLICY_FLAG_FILTERED;
3370 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3371 return; // event was consumed by the filter
3372 }
3373
3374 mLock.lock();
3375 }
3376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003378 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 args->displayId, policyFlags, args->action, flags, keyCode,
3380 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
3382 needWake = enqueueInboundEventLocked(newEntry);
3383 mLock.unlock();
3384 } // release lock
3385
3386 if (needWake) {
3387 mLooper->wake();
3388 }
3389}
3390
3391bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3392 return mInputFilterEnabled;
3393}
3394
3395void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3396#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003397 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3398 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003399 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3400 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003401 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003402 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3403 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3404 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3405 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 for (uint32_t i = 0; i < args->pointerCount; i++) {
3407 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 "x=%f, y=%f, pressure=%f, size=%f, "
3409 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3410 "orientation=%f",
3411 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3412 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3413 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3414 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3415 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3416 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3417 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3418 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3419 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3420 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3424 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 return;
3426 }
3427
3428 uint32_t policyFlags = args->policyFlags;
3429 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003430
3431 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003432 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003433 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3434 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437
3438 bool needWake;
3439 { // acquire lock
3440 mLock.lock();
3441
3442 if (shouldSendMotionToInputFilterLocked(args)) {
3443 mLock.unlock();
3444
3445 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003446 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003447 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3448 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003449 args->metaState, args->buttonState, args->classification, transform,
3450 args->xPrecision, args->yPrecision, args->xCursorPosition,
3451 args->yCursorPosition, args->downTime, args->eventTime,
3452 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453
3454 policyFlags |= POLICY_FLAG_FILTERED;
3455 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3456 return; // event was consumed by the filter
3457 }
3458
3459 mLock.lock();
3460 }
3461
3462 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003463 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003464 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003465 args->displayId, policyFlags, args->action, args->actionButton,
3466 args->flags, args->metaState, args->buttonState,
3467 args->classification, args->edgeFlags, args->xPrecision,
3468 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3469 args->downTime, args->pointerCount, args->pointerProperties,
3470 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
3472 needWake = enqueueInboundEventLocked(newEntry);
3473 mLock.unlock();
3474 } // release lock
3475
3476 if (needWake) {
3477 mLooper->wake();
3478 }
3479}
3480
3481bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003482 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483}
3484
3485void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3486#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003487 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 "switchMask=0x%08x",
3489 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490#endif
3491
3492 uint32_t policyFlags = args->policyFlags;
3493 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003494 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495}
3496
3497void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3498#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3500 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501#endif
3502
3503 bool needWake;
3504 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003505 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Prabir Pradhan42611e02018-11-27 14:04:02 -08003507 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003508 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 needWake = enqueueInboundEventLocked(newEntry);
3510 } // release lock
3511
3512 if (needWake) {
3513 mLooper->wake();
3514 }
3515}
3516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3518 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003519 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#if DEBUG_INBOUND_EVENT_DETAILS
3521 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003522 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3523 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003525 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
3527 policyFlags |= POLICY_FLAG_INJECTED;
3528 if (hasInjectionPermission(injectorPid, injectorUid)) {
3529 policyFlags |= POLICY_FLAG_TRUSTED;
3530 }
3531
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003532 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003535 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3536 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003537 if (!validateKeyEvent(action)) {
3538 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003541 int32_t flags = incomingKey.getFlags();
3542 int32_t keyCode = incomingKey.getKeyCode();
3543 int32_t metaState = incomingKey.getMetaState();
3544 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003545 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003546 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003547 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003548 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3549 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3550 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003552 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3553 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003554 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555
3556 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3557 android::base::Timer t;
3558 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3559 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3560 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3561 std::to_string(t.duration().count()).c_str());
3562 }
3563 }
3564
3565 mLock.lock();
3566 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003567 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3568 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003569 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3570 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003571 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 injectedEntries.push(injectedEntry);
3573 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 case AINPUT_EVENT_TYPE_MOTION: {
3577 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3578 int32_t action = motionEvent->getAction();
3579 size_t pointerCount = motionEvent->getPointerCount();
3580 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3581 int32_t actionButton = motionEvent->getActionButton();
3582 int32_t displayId = motionEvent->getDisplayId();
3583 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3584 return INPUT_EVENT_INJECTION_FAILED;
3585 }
3586
3587 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3588 nsecs_t eventTime = motionEvent->getEventTime();
3589 android::base::Timer t;
3590 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3591 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3592 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3593 std::to_string(t.duration().count()).c_str());
3594 }
3595 }
3596
3597 mLock.lock();
3598 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3599 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3600 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003601 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3602 motionEvent->getSource(), motionEvent->getDisplayId(),
3603 policyFlags, action, actionButton, motionEvent->getFlags(),
3604 motionEvent->getMetaState(), motionEvent->getButtonState(),
3605 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3606 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003607 motionEvent->getRawXCursorPosition(),
3608 motionEvent->getRawYCursorPosition(),
3609 motionEvent->getDownTime(), uint32_t(pointerCount),
3610 pointerProperties, samplePointerCoords,
3611 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 injectedEntries.push(injectedEntry);
3613 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3614 sampleEventTimes += 1;
3615 samplePointerCoords += pointerCount;
3616 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003617 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003618 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 motionEvent->getDisplayId(), policyFlags, action,
3620 actionButton, motionEvent->getFlags(),
3621 motionEvent->getMetaState(), motionEvent->getButtonState(),
3622 motionEvent->getClassification(),
3623 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3624 motionEvent->getYPrecision(),
3625 motionEvent->getRawXCursorPosition(),
3626 motionEvent->getRawYCursorPosition(),
3627 motionEvent->getDownTime(), uint32_t(pointerCount),
3628 pointerProperties, samplePointerCoords,
3629 motionEvent->getXOffset(), motionEvent->getYOffset());
3630 injectedEntries.push(nextInjectedEntry);
3631 }
3632 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003636 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639
3640 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3641 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3642 injectionState->injectionIsAsync = true;
3643 }
3644
3645 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003646 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
3648 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003649 while (!injectedEntries.empty()) {
3650 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3651 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653
3654 mLock.unlock();
3655
3656 if (needWake) {
3657 mLooper->wake();
3658 }
3659
3660 int32_t injectionResult;
3661 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003662 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663
3664 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3665 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3666 } else {
3667 for (;;) {
3668 injectionResult = injectionState->injectionResult;
3669 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3670 break;
3671 }
3672
3673 nsecs_t remainingTimeout = endTime - now();
3674 if (remainingTimeout <= 0) {
3675#if DEBUG_INJECTION
3676 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678#endif
3679 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3680 break;
3681 }
3682
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003683 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003686 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3687 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 while (injectionState->pendingForegroundDispatches != 0) {
3689#if DEBUG_INJECTION
3690 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003691 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692#endif
3693 nsecs_t remainingTimeout = endTime - now();
3694 if (remainingTimeout <= 0) {
3695#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003696 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3697 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698#endif
3699 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3700 break;
3701 }
3702
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003703 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705 }
3706 }
3707
3708 injectionState->release();
3709 } // release lock
3710
3711#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003712 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003713 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714#endif
3715
3716 return injectionResult;
3717}
3718
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003719std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003720 std::array<uint8_t, 32> calculatedHmac;
3721 std::unique_ptr<VerifiedInputEvent> result;
3722 switch (event.getType()) {
3723 case AINPUT_EVENT_TYPE_KEY: {
3724 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3725 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3726 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003727 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003728 break;
3729 }
3730 case AINPUT_EVENT_TYPE_MOTION: {
3731 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3732 VerifiedMotionEvent verifiedMotionEvent =
3733 verifiedMotionEventFromMotionEvent(motionEvent);
3734 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003735 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003736 break;
3737 }
3738 default: {
3739 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3740 return nullptr;
3741 }
3742 }
3743 if (calculatedHmac == INVALID_HMAC) {
3744 return nullptr;
3745 }
3746 if (calculatedHmac != event.getHmac()) {
3747 return nullptr;
3748 }
3749 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003753 return injectorUid == 0 ||
3754 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755}
3756
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003757void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t 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) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 case INPUT_EVENT_INJECTION_SUCCEEDED:
3770 ALOGV("Asynchronous input event injection succeeded.");
3771 break;
3772 case INPUT_EVENT_INJECTION_FAILED:
3773 ALOGW("Asynchronous input event injection failed.");
3774 break;
3775 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3776 ALOGW("Asynchronous input event injection permission denied.");
3777 break;
3778 case INPUT_EVENT_INJECTION_TIMED_OUT:
3779 ALOGW("Asynchronous input event injection timed out.");
3780 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
3782 }
3783
3784 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003785 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787}
3788
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003789void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 InjectionState* injectionState = entry->injectionState;
3791 if (injectionState) {
3792 injectionState->pendingForegroundDispatches += 1;
3793 }
3794}
3795
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003796void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 InjectionState* injectionState = entry->injectionState;
3798 if (injectionState) {
3799 injectionState->pendingForegroundDispatches -= 1;
3800
3801 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003802 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 }
3805}
3806
Vishnu Nairad321cd2020-08-20 16:40:21 -07003807const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003808 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003809 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3810 auto it = mWindowHandlesByDisplay.find(displayId);
3811 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003812}
3813
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003815 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003816 if (windowHandleToken == nullptr) {
3817 return nullptr;
3818 }
3819
Arthur Hungb92218b2018-08-14 12:00:21 +08003820 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003821 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003822 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003823 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003824 return windowHandle;
3825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 }
3827 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003828 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829}
3830
Vishnu Nairad321cd2020-08-20 16:40:21 -07003831sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3832 int displayId) const {
3833 if (windowHandleToken == nullptr) {
3834 return nullptr;
3835 }
3836
3837 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3838 if (windowHandle->getToken() == windowHandleToken) {
3839 return windowHandle;
3840 }
3841 }
3842 return nullptr;
3843}
3844
3845sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3846 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3847 return getWindowHandleLocked(focusedToken, displayId);
3848}
3849
Mady Mellor017bcd12020-06-23 19:12:00 +00003850bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3851 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003852 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003853 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003854 if (handle->getId() == windowHandle->getId() &&
3855 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003856 if (windowHandle->getInfo()->displayId != it.first) {
3857 ALOGE("Found window %s in display %" PRId32
3858 ", but it should belong to display %" PRId32,
3859 windowHandle->getName().c_str(), it.first,
3860 windowHandle->getInfo()->displayId);
3861 }
3862 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 }
3865 }
3866 return false;
3867}
3868
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003869bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3870 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3871 const bool noInputChannel =
3872 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3873 if (connection != nullptr && noInputChannel) {
3874 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3875 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3876 return false;
3877 }
3878
3879 if (connection == nullptr) {
3880 if (!noInputChannel) {
3881 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3882 }
3883 return false;
3884 }
3885 if (!connection->responsive) {
3886 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3887 return false;
3888 }
3889 return true;
3890}
3891
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003892std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3893 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003894 size_t count = mInputChannelsByToken.count(token);
3895 if (count == 0) {
3896 return nullptr;
3897 }
3898 return mInputChannelsByToken.at(token);
3899}
3900
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003901void InputDispatcher::updateWindowHandlesForDisplayLocked(
3902 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3903 if (inputWindowHandles.empty()) {
3904 // Remove all handles on a display if there are no windows left.
3905 mWindowHandlesByDisplay.erase(displayId);
3906 return;
3907 }
3908
3909 // Since we compare the pointer of input window handles across window updates, we need
3910 // to make sure the handle object for the same window stays unchanged across updates.
3911 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003912 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003913 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003914 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003915 }
3916
3917 std::vector<sp<InputWindowHandle>> newHandles;
3918 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3919 if (!handle->updateInfo()) {
3920 // handle no longer valid
3921 continue;
3922 }
3923
3924 const InputWindowInfo* info = handle->getInfo();
3925 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3926 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3927 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003928 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3929 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3930 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003931 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003932 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003933 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003934 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003935 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003936 }
3937
3938 if (info->displayId != displayId) {
3939 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3940 handle->getName().c_str(), displayId, info->displayId);
3941 continue;
3942 }
3943
Robert Carredd13602020-04-13 17:24:34 -07003944 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3945 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003946 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003947 oldHandle->updateFrom(handle);
3948 newHandles.push_back(oldHandle);
3949 } else {
3950 newHandles.push_back(handle);
3951 }
3952 }
3953
3954 // Insert or replace
3955 mWindowHandlesByDisplay[displayId] = newHandles;
3956}
3957
Arthur Hung72d8dc32020-03-28 00:48:39 +00003958void InputDispatcher::setInputWindows(
3959 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3960 { // acquire lock
3961 std::scoped_lock _l(mLock);
3962 for (auto const& i : handlesPerDisplay) {
3963 setInputWindowsLocked(i.second, i.first);
3964 }
3965 }
3966 // Wake up poll loop since it may need to make new input dispatching choices.
3967 mLooper->wake();
3968}
3969
Arthur Hungb92218b2018-08-14 12:00:21 +08003970/**
3971 * Called from InputManagerService, update window handle list by displayId that can receive input.
3972 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3973 * If set an empty list, remove all handles from the specific display.
3974 * For focused handle, check if need to change and send a cancel event to previous one.
3975 * For removed handle, check if need to send a cancel event if already in touch.
3976 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003977void InputDispatcher::setInputWindowsLocked(
3978 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003979 if (DEBUG_FOCUS) {
3980 std::string windowList;
3981 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3982 windowList += iwh->getName() + " ";
3983 }
3984 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003987 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3988 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3989 const bool noInputWindow =
3990 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3991 if (noInputWindow && window->getToken() != nullptr) {
3992 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3993 window->getName().c_str());
3994 window->releaseChannel();
3995 }
3996 }
3997
Arthur Hung72d8dc32020-03-28 00:48:39 +00003998 // Copy old handles for release if they are no longer present.
3999 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
Arthur Hung72d8dc32020-03-28 00:48:39 +00004001 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004002
Vishnu Nair958da932020-08-21 17:12:37 -07004003 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4004 if (mLastHoverWindowHandle &&
4005 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4006 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004007 mLastHoverWindowHandle = nullptr;
4008 }
4009
Vishnu Nair958da932020-08-21 17:12:37 -07004010 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4011 if (focusedToken) {
4012 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4013 if (result != FocusResult::OK) {
4014 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4015 }
4016 }
4017
4018 std::optional<FocusRequest> focusRequest =
4019 getOptionalValueByKey(mPendingFocusRequests, displayId);
4020 if (focusRequest) {
4021 // If the window from the pending request is now visible, provide it focus.
4022 FocusResult result = handleFocusRequestLocked(*focusRequest);
4023 if (result != FocusResult::NOT_VISIBLE) {
4024 // Drop the request if we were able to change the focus or we cannot change
4025 // it for another reason.
4026 mPendingFocusRequests.erase(displayId);
4027 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004030 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4031 mTouchStatesByDisplay.find(displayId);
4032 if (stateIt != mTouchStatesByDisplay.end()) {
4033 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004034 for (size_t i = 0; i < state.windows.size();) {
4035 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004036 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004037 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004038 ALOGD("Touched window was removed: %s in display %" PRId32,
4039 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004040 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004041 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004042 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4043 if (touchedInputChannel != nullptr) {
4044 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4045 "touched window was removed");
4046 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004048 state.windows.erase(state.windows.begin() + i);
4049 } else {
4050 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
4052 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004053 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004054
Arthur Hung72d8dc32020-03-28 00:48:39 +00004055 // Release information for windows that are no longer present.
4056 // This ensures that unused input channels are released promptly.
4057 // Otherwise, they might stick around until the window handle is destroyed
4058 // which might not happen until the next GC.
4059 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004060 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004061 if (DEBUG_FOCUS) {
4062 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004063 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004064 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004065 }
chaviw291d88a2019-02-14 10:33:58 -08004066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067}
4068
4069void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004070 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004071 if (DEBUG_FOCUS) {
4072 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4073 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4074 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004075 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004076 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Chris Yea209fde2020-07-22 13:54:51 -07004078 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004079 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004080
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004081 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4082 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004083 }
4084
Chris Yea209fde2020-07-22 13:54:51 -07004085 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004086 if (inputApplicationHandle != nullptr) {
4087 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4088 } else {
4089 mFocusedApplicationHandlesByDisplay.erase(displayId);
4090 }
4091
4092 // No matter what the old focused application was, stop waiting on it because it is
4093 // no longer focused.
4094 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 } // release lock
4096
4097 // Wake up poll loop since it may need to make new input dispatching choices.
4098 mLooper->wake();
4099}
4100
Tiger Huang721e26f2018-07-24 22:26:19 +08004101/**
4102 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4103 * the display not specified.
4104 *
4105 * We track any unreleased events for each window. If a window loses the ability to receive the
4106 * released event, we will send a cancel event to it. So when the focused display is changed, we
4107 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4108 * display. The display-specified events won't be affected.
4109 */
4110void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004111 if (DEBUG_FOCUS) {
4112 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4113 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004114 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004115 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004116
4117 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004118 sp<IBinder> oldFocusedWindowToken =
4119 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4120 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004121 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004122 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004123 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 CancelationOptions
4125 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4126 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004127 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004128 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4129 }
4130 }
4131 mFocusedDisplayId = displayId;
4132
Chris Ye3c2d6f52020-08-09 10:39:48 -07004133 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004134 sp<IBinder> newFocusedWindowToken =
4135 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4136 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004137
Vishnu Nairad321cd2020-08-20 16:40:21 -07004138 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004139 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004140 if (!mFocusedWindowTokenByDisplay.empty()) {
4141 ALOGE("But another display has a focused window\n%s",
4142 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004143 }
4144 }
4145 }
4146
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004147 if (DEBUG_FOCUS) {
4148 logDispatchStateLocked();
4149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004150 } // release lock
4151
4152 // Wake up poll loop since it may need to make new input dispatching choices.
4153 mLooper->wake();
4154}
4155
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004157 if (DEBUG_FOCUS) {
4158 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160
4161 bool changed;
4162 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004163 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4166 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004167 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
4170 if (mDispatchEnabled && !enabled) {
4171 resetAndDropEverythingLocked("dispatcher is being disabled");
4172 }
4173
4174 mDispatchEnabled = enabled;
4175 mDispatchFrozen = frozen;
4176 changed = true;
4177 } else {
4178 changed = false;
4179 }
4180
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004181 if (DEBUG_FOCUS) {
4182 logDispatchStateLocked();
4183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 } // release lock
4185
4186 if (changed) {
4187 // Wake up poll loop since it may need to make new input dispatching choices.
4188 mLooper->wake();
4189 }
4190}
4191
4192void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004193 if (DEBUG_FOCUS) {
4194 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
4197 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004198 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
4200 if (mInputFilterEnabled == enabled) {
4201 return;
4202 }
4203
4204 mInputFilterEnabled = enabled;
4205 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4206 } // release lock
4207
4208 // Wake up poll loop since there might be work to do to drop everything.
4209 mLooper->wake();
4210}
4211
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004212void InputDispatcher::setInTouchMode(bool inTouchMode) {
4213 std::scoped_lock lock(mLock);
4214 mInTouchMode = inTouchMode;
4215}
4216
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004217void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4218 if (opacity < 0 || opacity > 1) {
4219 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4220 return;
4221 }
4222
4223 std::scoped_lock lock(mLock);
4224 mMaximumObscuringOpacityForTouch = opacity;
4225}
4226
4227void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4228 std::scoped_lock lock(mLock);
4229 mBlockUntrustedTouchesMode = mode;
4230}
4231
chaviwfbe5d9c2018-12-26 12:23:37 -08004232bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4233 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004234 if (DEBUG_FOCUS) {
4235 ALOGD("Trivial transfer to same window.");
4236 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004237 return true;
4238 }
4239
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004241 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
chaviwfbe5d9c2018-12-26 12:23:37 -08004243 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4244 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004245 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004246 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 return false;
4248 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004249 if (DEBUG_FOCUS) {
4250 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4251 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004254 if (DEBUG_FOCUS) {
4255 ALOGD("Cannot transfer focus because windows are on different displays.");
4256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 return false;
4258 }
4259
4260 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004261 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4262 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004263 for (size_t i = 0; i < state.windows.size(); i++) {
4264 const TouchedWindow& touchedWindow = state.windows[i];
4265 if (touchedWindow.windowHandle == fromWindowHandle) {
4266 int32_t oldTargetFlags = touchedWindow.targetFlags;
4267 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004269 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 int32_t newTargetFlags = oldTargetFlags &
4272 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4273 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004274 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Jeff Brownf086ddb2014-02-11 14:28:48 -08004276 found = true;
4277 goto Found;
4278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004284 if (DEBUG_FOCUS) {
4285 ALOGD("Focus transfer failed because from window did not have focus.");
4286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 return false;
4288 }
4289
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004290 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4291 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004292 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004293 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 CancelationOptions
4295 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4296 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004298 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 }
4300
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004301 if (DEBUG_FOCUS) {
4302 logDispatchStateLocked();
4303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 } // release lock
4305
4306 // Wake up poll loop since it may need to make new input dispatching choices.
4307 mLooper->wake();
4308 return true;
4309}
4310
4311void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004312 if (DEBUG_FOCUS) {
4313 ALOGD("Resetting and dropping all events (%s).", reason);
4314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
4316 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4317 synthesizeCancelationEventsForAllConnectionsLocked(options);
4318
4319 resetKeyRepeatLocked();
4320 releasePendingEventLocked();
4321 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004322 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004324 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004325 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004327 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328}
4329
4330void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004331 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 dumpDispatchStateLocked(dump);
4333
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334 std::istringstream stream(dump);
4335 std::string line;
4336
4337 while (std::getline(stream, line, '\n')) {
4338 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340}
4341
Vishnu Nairad321cd2020-08-20 16:40:21 -07004342std::string InputDispatcher::dumpFocusedWindowsLocked() {
4343 if (mFocusedWindowTokenByDisplay.empty()) {
4344 return INDENT "FocusedWindows: <none>\n";
4345 }
4346
4347 std::string dump;
4348 dump += INDENT "FocusedWindows:\n";
4349 for (auto& it : mFocusedWindowTokenByDisplay) {
4350 const int32_t displayId = it.first;
4351 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4352 if (windowHandle) {
4353 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4354 windowHandle->getName().c_str());
4355 } else {
4356 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4357 " has focused token without a window'\n",
4358 displayId);
4359 }
4360 }
4361 return dump;
4362}
4363
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004364void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004365 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4366 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4367 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004368 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
Tiger Huang721e26f2018-07-24 22:26:19 +08004370 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4371 dump += StringPrintf(INDENT "FocusedApplications:\n");
4372 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4373 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004374 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004375 const std::chrono::duration timeout =
4376 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004378 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004379 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004382 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004384
Vishnu Nairad321cd2020-08-20 16:40:21 -07004385 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004387 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004388 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004389 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4390 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004391 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 state.displayId, toString(state.down), toString(state.split),
4393 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004394 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004395 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004396 for (size_t i = 0; i < state.windows.size(); i++) {
4397 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 dump += StringPrintf(INDENT4
4399 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4400 i, touchedWindow.windowHandle->getName().c_str(),
4401 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004402 }
4403 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004404 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004405 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004406 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004407 dump += INDENT3 "Portal windows:\n";
4408 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004409 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4411 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004412 }
4413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 }
4415 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004416 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418
Arthur Hungb92218b2018-08-14 12:00:21 +08004419 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004421 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004422 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004423 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004424 dump += INDENT2 "Windows:\n";
4425 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004426 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004427 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Arthur Hungb92218b2018-08-14 12:00:21 +08004429 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004430 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4431 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004432 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004434 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004435 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 i, windowInfo->name.c_str(), windowInfo->displayId,
4437 windowInfo->portalToDisplayId,
4438 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004439 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 toString(windowInfo->hasWallpaper),
4441 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004442 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004443 static_cast<int32_t>(windowInfo->type),
4444 windowInfo->frameLeft, windowInfo->frameTop,
4445 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004446 windowInfo->globalScaleFactor,
4447 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004448 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004449 dump += StringPrintf(", inputFeatures=%s",
4450 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004451 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4452 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004453 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004454 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004455 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004456 }
4457 } else {
4458 dump += INDENT2 "Windows: <none>\n";
4459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
4461 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004462 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 }
4464
Michael Wright3dd60e22019-03-27 22:06:44 +00004465 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004467 const std::vector<Monitor>& monitors = it.second;
4468 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4469 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470 }
4471 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004472 const std::vector<Monitor>& monitors = it.second;
4473 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4474 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004477 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 }
4479
4480 nsecs_t currentTime = now();
4481
4482 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004483 if (!mRecentQueue.empty()) {
4484 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4485 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004486 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004487 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 }
4490 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004491 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
4493
4494 // Dump event currently being dispatched.
4495 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004496 dump += INDENT "PendingEvent:\n";
4497 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004498 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004499 dump += StringPrintf(", age=%" PRId64 "ms\n",
4500 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004502 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
4504
4505 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004506 if (!mInboundQueue.empty()) {
4507 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4508 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004509 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004510 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004511 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004514 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004517 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004518 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004519 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4520 const KeyReplacement& replacement = pair.first;
4521 int32_t newKeyCode = pair.second;
4522 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004524 }
4525 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004526 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004527 }
4528
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004529 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004530 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004531 for (const auto& pair : mConnectionsByFd) {
4532 const sp<Connection>& connection = pair.second;
4533 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004534 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004535 pair.first, connection->getInputChannelName().c_str(),
4536 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004539 if (!connection->outboundQueue.empty()) {
4540 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4541 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004542 dump += dumpQueue(connection->outboundQueue, currentTime);
4543
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004545 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004548 if (!connection->waitQueue.empty()) {
4549 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4550 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004551 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004553 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 }
4555 }
4556 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004557 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559
4560 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004561 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4562 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004564 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
4566
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004567 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004568 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4569 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4570 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571}
4572
Michael Wright3dd60e22019-03-27 22:06:44 +00004573void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4574 const size_t numMonitors = monitors.size();
4575 for (size_t i = 0; i < numMonitors; i++) {
4576 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004577 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004578 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4579 dump += "\n";
4580 }
4581}
4582
Garfield Tan15601662020-09-22 15:32:38 -07004583base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4584 const std::string& name) {
4585#if DEBUG_CHANNEL_CREATION
4586 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587#endif
4588
Garfield Tan15601662020-09-22 15:32:38 -07004589 std::shared_ptr<InputChannel> serverChannel;
4590 std::unique_ptr<InputChannel> clientChannel;
4591 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4592
4593 if (result) {
4594 return base::Error(result) << "Failed to open input channel pair with name " << name;
4595 }
4596
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004598 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004599 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
Garfield Tan15601662020-09-22 15:32:38 -07004601 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004602 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004603 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4606 } // release lock
4607
4608 // Wake the looper because some connections have changed.
4609 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004610 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611}
4612
Garfield Tan15601662020-09-22 15:32:38 -07004613base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4614 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4615 std::shared_ptr<InputChannel> serverChannel;
4616 std::unique_ptr<InputChannel> clientChannel;
4617 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4618 if (result) {
4619 return base::Error(result) << "Failed to open input channel pair with name " << name;
4620 }
4621
Michael Wright3dd60e22019-03-27 22:06:44 +00004622 { // acquire lock
4623 std::scoped_lock _l(mLock);
4624
4625 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004626 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4627 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004628 }
4629
Garfield Tan15601662020-09-22 15:32:38 -07004630 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004631
Garfield Tan15601662020-09-22 15:32:38 -07004632 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004633 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004634 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004636 auto& monitorsByDisplay =
4637 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004638 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004639
4640 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004641 }
Garfield Tan15601662020-09-22 15:32:38 -07004642
Michael Wright3dd60e22019-03-27 22:06:44 +00004643 // Wake the looper because some connections have changed.
4644 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004645 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004646}
4647
Garfield Tan15601662020-09-22 15:32:38 -07004648status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004650 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651
Garfield Tan15601662020-09-22 15:32:38 -07004652 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 if (status) {
4654 return status;
4655 }
4656 } // release lock
4657
4658 // Wake the poll loop because removing the connection may have changed the current
4659 // synchronization state.
4660 mLooper->wake();
4661 return OK;
4662}
4663
Garfield Tan15601662020-09-22 15:32:38 -07004664status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4665 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004666 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004667 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004668 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 return BAD_VALUE;
4670 }
4671
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004672 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004673 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004674
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004676 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 }
4678
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004679 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680
4681 nsecs_t currentTime = now();
4682 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4683
4684 connection->status = Connection::STATUS_ZOMBIE;
4685 return OK;
4686}
4687
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004688void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4689 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4690 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004691}
4692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004694 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004695 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004697 std::vector<Monitor>& monitors = it->second;
4698 const size_t numMonitors = monitors.size();
4699 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004700 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701 monitors.erase(monitors.begin() + i);
4702 break;
4703 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004704 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004705 if (monitors.empty()) {
4706 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004707 } else {
4708 ++it;
4709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 }
4711}
4712
Michael Wright3dd60e22019-03-27 22:06:44 +00004713status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4714 { // acquire lock
4715 std::scoped_lock _l(mLock);
4716 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4717
4718 if (!foundDisplayId) {
4719 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4720 return BAD_VALUE;
4721 }
4722 int32_t displayId = foundDisplayId.value();
4723
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004724 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4725 mTouchStatesByDisplay.find(displayId);
4726 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004727 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4728 return BAD_VALUE;
4729 }
4730
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004731 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004732 std::optional<int32_t> foundDeviceId;
4733 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004734 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004735 foundDeviceId = state.deviceId;
4736 }
4737 }
4738 if (!foundDeviceId || !state.down) {
4739 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004740 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004741 return BAD_VALUE;
4742 }
4743 int32_t deviceId = foundDeviceId.value();
4744
4745 // Send cancel events to all the input channels we're stealing from.
4746 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004747 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004748 options.deviceId = deviceId;
4749 options.displayId = displayId;
4750 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004751 std::shared_ptr<InputChannel> channel =
4752 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004753 if (channel != nullptr) {
4754 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4755 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004756 }
4757 // Then clear the current touch state so we stop dispatching to them as well.
4758 state.filterNonMonitors();
4759 }
4760 return OK;
4761}
4762
Michael Wright3dd60e22019-03-27 22:06:44 +00004763std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4764 const sp<IBinder>& token) {
4765 for (const auto& it : mGestureMonitorsByDisplay) {
4766 const std::vector<Monitor>& monitors = it.second;
4767 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004768 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004769 return it.first;
4770 }
4771 }
4772 }
4773 return std::nullopt;
4774}
4775
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004776sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004777 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004778 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004779 }
4780
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004781 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004782 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004783 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004784 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 }
4786 }
Robert Carr4e670e52018-08-15 13:26:12 -07004787
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004788 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789}
4790
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004791void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004793 removeByValue(mConnectionsByFd, connection);
4794}
4795
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4797 const sp<Connection>& connection, uint32_t seq,
4798 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004799 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4800 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 commandEntry->connection = connection;
4802 commandEntry->eventTime = currentTime;
4803 commandEntry->seq = seq;
4804 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004805 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806}
4807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4809 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004811 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004813 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4814 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004816 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817}
4818
Vishnu Nairad321cd2020-08-20 16:40:21 -07004819void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4820 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004821 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4822 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004823 commandEntry->oldToken = oldToken;
4824 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004825 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004826}
4827
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004828void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4830 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004831 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004833 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834 return;
4835 }
4836 /**
4837 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4838 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4839 * has changed. This could cause newer entries to time out before the already dispatched
4840 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4841 * processes the events linearly. So providing information about the oldest entry seems to be
4842 * most useful.
4843 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004844 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004845 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4846 std::string reason =
4847 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004848 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 ns2ms(currentWait),
4850 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004852 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853 reason);
4854
4855 std::unique_ptr<CommandEntry> commandEntry =
4856 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4857 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004858 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859 commandEntry->reason = std::move(reason);
4860 postCommandLocked(std::move(commandEntry));
4861}
4862
Chris Yea209fde2020-07-22 13:54:51 -07004863void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4865 application->getName().c_str());
4866
4867 updateLastAnrStateLocked(application, reason);
4868
4869 std::unique_ptr<CommandEntry> commandEntry =
4870 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4871 commandEntry->inputApplicationHandle = application;
4872 commandEntry->inputChannel = nullptr;
4873 commandEntry->reason = std::move(reason);
4874 postCommandLocked(std::move(commandEntry));
4875}
4876
4877void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4878 const std::string& reason) {
4879 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4880 updateLastAnrStateLocked(windowLabel, reason);
4881}
4882
Chris Yea209fde2020-07-22 13:54:51 -07004883void InputDispatcher::updateLastAnrStateLocked(
4884 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4886 updateLastAnrStateLocked(windowLabel, reason);
4887}
4888
4889void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4890 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004892 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 struct tm tm;
4894 localtime_r(&t, &tm);
4895 char timestr[64];
4896 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004897 mLastAnrState.clear();
4898 mLastAnrState += INDENT "ANR:\n";
4899 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004900 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4901 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004902 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903}
4904
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004905void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 mLock.unlock();
4907
4908 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4909
4910 mLock.lock();
4911}
4912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 sp<Connection> connection = commandEntry->connection;
4915
4916 if (connection->status != Connection::STATUS_ZOMBIE) {
4917 mLock.unlock();
4918
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004919 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
4921 mLock.lock();
4922 }
4923}
4924
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004925void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004926 sp<IBinder> oldToken = commandEntry->oldToken;
4927 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004928 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004929 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004930 mLock.lock();
4931}
4932
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004933void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004934 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004935 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 mLock.unlock();
4937
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004938 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004939 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940
4941 mLock.lock();
4942
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004943 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004944 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4945 } else {
4946 // stop waking up for events in this connection, it is already not responding
4947 sp<Connection> connection = getConnectionLocked(token);
4948 if (connection == nullptr) {
4949 return;
4950 }
4951 cancelEventsForAnrLocked(connection);
4952 }
4953}
4954
Chris Yea209fde2020-07-22 13:54:51 -07004955void InputDispatcher::extendAnrTimeoutsLocked(
4956 const std::shared_ptr<InputApplicationHandle>& application,
4957 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004958 if (connectionToken == nullptr && application != nullptr) {
4959 // The ANR happened because there's no focused window
4960 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4961 mAwaitedFocusedApplication = application;
4962 }
4963
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004964 sp<Connection> connection = getConnectionLocked(connectionToken);
4965 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004966 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004967 return;
4968 }
4969
4970 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004971 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004972
4973 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004974 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 for (DispatchEntry* entry : connection->waitQueue) {
4976 if (newTimeout >= entry->timeoutTime) {
4977 // Already removed old entries when connection was marked unresponsive
4978 entry->timeoutTime = newTimeout;
4979 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4980 }
4981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982}
4983
4984void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4985 CommandEntry* commandEntry) {
4986 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004987 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988
4989 mLock.unlock();
4990
Michael Wright2b3c3302018-03-02 17:19:13 +00004991 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004992 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004993 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 : nullptr;
4995 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004996 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4997 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004998 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000
5001 mLock.lock();
5002
5003 if (delay < 0) {
5004 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5005 } else if (!delay) {
5006 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5007 } else {
5008 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5009 entry->interceptKeyWakeupTime = now() + delay;
5010 }
5011 entry->release();
5012}
5013
chaviwfd6d3512019-03-25 13:23:49 -07005014void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5015 mLock.unlock();
5016 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5017 mLock.lock();
5018}
5019
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020/**
5021 * Connection is responsive if it has no events in the waitQueue that are older than the
5022 * current time.
5023 */
5024static bool isConnectionResponsive(const Connection& connection) {
5025 const nsecs_t currentTime = now();
5026 for (const DispatchEntry* entry : connection.waitQueue) {
5027 if (entry->timeoutTime < currentTime) {
5028 return false;
5029 }
5030 }
5031 return true;
5032}
5033
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005036 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005038 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039
5040 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005041 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005042 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005043 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005045 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005046 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005047 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005048 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5049 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005050 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005051 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005052
5053 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005054 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005055 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5056 restartEvent =
5057 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005058 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005059 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5060 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5061 handled);
5062 } else {
5063 restartEvent = false;
5064 }
5065
5066 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005067 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005068 // contents of the wait queue to have been drained, so we need to double-check
5069 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005070 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5071 if (dispatchEntryIt != connection->waitQueue.end()) {
5072 dispatchEntry = *dispatchEntryIt;
5073 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005074 mAnrTracker.erase(dispatchEntry->timeoutTime,
5075 connection->inputChannel->getConnectionToken());
5076 if (!connection->responsive) {
5077 connection->responsive = isConnectionResponsive(*connection);
5078 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005079 traceWaitQueueLength(connection);
5080 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005081 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005082 traceOutboundQueueLength(connection);
5083 } else {
5084 releaseDispatchEntry(dispatchEntry);
5085 }
5086 }
5087
5088 // Start the next dispatch cycle for this connection.
5089 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090}
5091
5092bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005093 DispatchEntry* dispatchEntry,
5094 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005095 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005096 if (!handled) {
5097 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005098 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005099 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005100 return false;
5101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005103 // Get the fallback key state.
5104 // Clear it out after dispatching the UP.
5105 int32_t originalKeyCode = keyEntry->keyCode;
5106 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5107 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5108 connection->inputState.removeFallbackKey(originalKeyCode);
5109 }
5110
5111 if (handled || !dispatchEntry->hasForegroundTarget()) {
5112 // If the application handles the original key for which we previously
5113 // generated a fallback or if the window is not a foreground window,
5114 // then cancel the associated fallback key, if any.
5115 if (fallbackKeyCode != -1) {
5116 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005118 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005119 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5120 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5121 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005123 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005124 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125
5126 mLock.unlock();
5127
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005128 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005129 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
5131 mLock.lock();
5132
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005133 // Cancel the fallback key.
5134 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005136 "application handled the original non-fallback key "
5137 "or is no longer a foreground target, "
5138 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 options.keyCode = fallbackKeyCode;
5140 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005142 connection->inputState.removeFallbackKey(originalKeyCode);
5143 }
5144 } else {
5145 // If the application did not handle a non-fallback key, first check
5146 // that we are in a good state to perform unhandled key event processing
5147 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005148 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005149 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005151 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005152 "since this is not an initial down. "
5153 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5154 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005156 return false;
5157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005159 // Dispatch the unhandled key to the policy.
5160#if DEBUG_OUTBOUND_EVENT_DETAILS
5161 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005162 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5163 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005164#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005165 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005166
5167 mLock.unlock();
5168
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005169 bool fallback =
5170 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5171 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005172
5173 mLock.lock();
5174
5175 if (connection->status != Connection::STATUS_NORMAL) {
5176 connection->inputState.removeFallbackKey(originalKeyCode);
5177 return false;
5178 }
5179
5180 // Latch the fallback keycode for this key on an initial down.
5181 // The fallback keycode cannot change at any other point in the lifecycle.
5182 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005184 fallbackKeyCode = event.getKeyCode();
5185 } else {
5186 fallbackKeyCode = AKEYCODE_UNKNOWN;
5187 }
5188 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5189 }
5190
5191 ALOG_ASSERT(fallbackKeyCode != -1);
5192
5193 // Cancel the fallback key if the policy decides not to send it anymore.
5194 // We will continue to dispatch the key to the policy but we will no
5195 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005196 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5197 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005198#if DEBUG_OUTBOUND_EVENT_DETAILS
5199 if (fallback) {
5200 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005201 "as a fallback for %d, but on the DOWN it had requested "
5202 "to send %d instead. Fallback canceled.",
5203 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005204 } else {
5205 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005206 "but on the DOWN it had requested to send %d. "
5207 "Fallback canceled.",
5208 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005209 }
5210#endif
5211
5212 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5213 "canceling fallback, policy no longer desires it");
5214 options.keyCode = fallbackKeyCode;
5215 synthesizeCancelationEventsForConnectionLocked(connection, options);
5216
5217 fallback = false;
5218 fallbackKeyCode = AKEYCODE_UNKNOWN;
5219 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005220 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005221 }
5222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223
5224#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005225 {
5226 std::string msg;
5227 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5228 connection->inputState.getFallbackKeys();
5229 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005230 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005232 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005233 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005234 }
5235#endif
5236
5237 if (fallback) {
5238 // Restart the dispatch cycle using the fallback key.
5239 keyEntry->eventTime = event.getEventTime();
5240 keyEntry->deviceId = event.getDeviceId();
5241 keyEntry->source = event.getSource();
5242 keyEntry->displayId = event.getDisplayId();
5243 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5244 keyEntry->keyCode = fallbackKeyCode;
5245 keyEntry->scanCode = event.getScanCode();
5246 keyEntry->metaState = event.getMetaState();
5247 keyEntry->repeatCount = event.getRepeatCount();
5248 keyEntry->downTime = event.getDownTime();
5249 keyEntry->syntheticRepeat = false;
5250
5251#if DEBUG_OUTBOUND_EVENT_DETAILS
5252 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005253 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5254 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005255#endif
5256 return true; // restart the event
5257 } else {
5258#if DEBUG_OUTBOUND_EVENT_DETAILS
5259 ALOGD("Unhandled key event: No fallback key.");
5260#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005261
5262 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005263 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 }
5265 }
5266 return false;
5267}
5268
5269bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005270 DispatchEntry* dispatchEntry,
5271 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 return false;
5273}
5274
5275void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5276 mLock.unlock();
5277
5278 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5279
5280 mLock.lock();
5281}
5282
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005283KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5284 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005285 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005286 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5287 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005288 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289}
5290
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005291void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5292 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 // TODO Write some statistics about how long we spend waiting.
5294}
5295
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005296/**
5297 * Report the touch event latency to the statsd server.
5298 * Input events are reported for statistics if:
5299 * - This is a touchscreen event
5300 * - InputFilter is not enabled
5301 * - Event is not injected or synthesized
5302 *
5303 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5304 * from getting aggregated with the "old" data.
5305 */
5306void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5307 REQUIRES(mLock) {
5308 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5309 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5310 if (!reportForStatistics) {
5311 return;
5312 }
5313
5314 if (mTouchStatistics.shouldReport()) {
5315 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5316 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5317 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5318 mTouchStatistics.reset();
5319 }
5320 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5321 mTouchStatistics.addValue(latencyMicros);
5322}
5323
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324void InputDispatcher::traceInboundQueueLengthLocked() {
5325 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005326 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328}
5329
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005330void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 if (ATRACE_ENABLED()) {
5332 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005333 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005334 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336}
5337
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005338void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 if (ATRACE_ENABLED()) {
5340 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005341 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005342 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 }
5344}
5345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005346void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005347 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005349 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 dumpDispatchStateLocked(dump);
5351
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005352 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005353 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005354 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 }
5356}
5357
5358void InputDispatcher::monitor() {
5359 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005360 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005362 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363}
5364
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005365/**
5366 * Wake up the dispatcher and wait until it processes all events and commands.
5367 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5368 * this method can be safely called from any thread, as long as you've ensured that
5369 * the work you are interested in completing has already been queued.
5370 */
5371bool InputDispatcher::waitForIdle() {
5372 /**
5373 * Timeout should represent the longest possible time that a device might spend processing
5374 * events and commands.
5375 */
5376 constexpr std::chrono::duration TIMEOUT = 100ms;
5377 std::unique_lock lock(mLock);
5378 mLooper->wake();
5379 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5380 return result == std::cv_status::no_timeout;
5381}
5382
Vishnu Naire798b472020-07-23 13:52:21 -07005383/**
5384 * Sets focus to the window identified by the token. This must be called
5385 * after updating any input window handles.
5386 *
5387 * Params:
5388 * request.token - input channel token used to identify the window that should gain focus.
5389 * request.focusedToken - the token that the caller expects currently to be focused. If the
5390 * specified token does not match the currently focused window, this request will be dropped.
5391 * If the specified focused token matches the currently focused window, the call will succeed.
5392 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5393 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5394 * when requesting the focus change. This determines which request gets
5395 * precedence if there is a focus change request from another source such as pointer down.
5396 */
Vishnu Nair958da932020-08-21 17:12:37 -07005397void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5398 { // acquire lock
5399 std::scoped_lock _l(mLock);
5400
5401 const int32_t displayId = request.displayId;
5402 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5403 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5404 ALOGD_IF(DEBUG_FOCUS,
5405 "setFocusedWindow on display %" PRId32
5406 " ignored, reason: focusedToken is not focused",
5407 displayId);
5408 return;
5409 }
5410
5411 mPendingFocusRequests.erase(displayId);
5412 FocusResult result = handleFocusRequestLocked(request);
5413 if (result == FocusResult::NOT_VISIBLE) {
5414 // The requested window is not currently visible. Wait for the window to become visible
5415 // and then provide it focus. This is to handle situations where a user action triggers
5416 // a new window to appear. We want to be able to queue any key events after the user
5417 // action and deliver it to the newly focused window. In order for this to happen, we
5418 // take focus from the currently focused window so key events can be queued.
5419 ALOGD_IF(DEBUG_FOCUS,
5420 "setFocusedWindow on display %" PRId32
5421 " pending, reason: window is not visible",
5422 displayId);
5423 mPendingFocusRequests[displayId] = request;
5424 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5425 "setFocusedWindow_AwaitingWindowVisibility");
5426 } else if (result != FocusResult::OK) {
5427 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5428 typeToString(result));
5429 }
5430 } // release lock
5431 // Wake up poll loop since it may need to make new input dispatching choices.
5432 mLooper->wake();
5433}
5434
5435InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5436 const FocusRequest& request) {
5437 const int32_t displayId = request.displayId;
5438 const sp<IBinder> newFocusedToken = request.token;
5439 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5440
5441 if (oldFocusedToken == request.token) {
5442 ALOGD_IF(DEBUG_FOCUS,
5443 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5444 displayId);
5445 return FocusResult::OK;
5446 }
5447
5448 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5449 if (result != FocusResult::OK) {
5450 return result;
5451 }
5452
5453 std::string_view reason =
5454 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5455 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5456 return FocusResult::OK;
5457}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005458
Vishnu Nairad321cd2020-08-20 16:40:21 -07005459void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5460 const sp<IBinder>& newFocusedToken, int32_t displayId,
5461 std::string_view reason) {
5462 if (oldFocusedToken) {
5463 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005464 if (focusedInputChannel) {
5465 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5466 "focus left window");
5467 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005468 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005469 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005470 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005471 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005472 if (newFocusedToken) {
5473 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5474 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005475 }
5476
5477 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005478 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005479 }
5480}
Vishnu Nair958da932020-08-21 17:12:37 -07005481
5482/**
5483 * Checks if the window token can be focused on a display. The token can be focused if there is
5484 * at least one window handle that is visible with the same token and all window handles with the
5485 * same token are focusable.
5486 *
5487 * In the case of mirroring, two windows may share the same window token and their visibility
5488 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5489 * we expect the focusability of the windows to match since its hard to reason why one window can
5490 * receive focus events and the other cannot when both are backed by the same input channel.
5491 */
5492InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5493 int32_t displayId) const {
5494 bool allWindowsAreFocusable = true;
5495 bool visibleWindowFound = false;
5496 bool windowFound = false;
5497 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5498 if (window->getToken() != token) {
5499 continue;
5500 }
5501 windowFound = true;
5502 if (window->getInfo()->visible) {
5503 // Check if at least a single window is visible.
5504 visibleWindowFound = true;
5505 }
5506 if (!window->getInfo()->focusable) {
5507 // Check if all windows with the window token are focusable.
5508 allWindowsAreFocusable = false;
5509 break;
5510 }
5511 }
5512
5513 if (!windowFound) {
5514 return FocusResult::NO_WINDOW;
5515 }
5516 if (!allWindowsAreFocusable) {
5517 return FocusResult::NOT_FOCUSABLE;
5518 }
5519 if (!visibleWindowFound) {
5520 return FocusResult::NOT_VISIBLE;
5521 }
5522
5523 return FocusResult::OK;
5524}
Garfield Tane84e6f92019-08-29 17:28:41 -07005525} // namespace android::inputdispatcher