blob: a2582a5d7f2f37e6ce926b5c55fbc14519d07a83 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080077using android::os::BlockUntrustedTouchesMode;
78using android::os::InputEventInjectionResult;
79using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080080
Garfield Tane84e6f92019-08-29 17:28:41 -070081namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Default input dispatching timeout if there is no focused application or paused window
84// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050085constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
86 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for all pending events to be processed when an app switch
89// key is on the way. This is used to preempt input dispatch and drop input events
90// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Amount of time to allow for an event to be dispatched (measured since its eventTime)
94// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Michael Wrightd02c5b62014-02-10 15:10:22 -080097// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
99
100// Log a warning when an interception call takes longer than this to process.
101constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700103// Additional key latency in case a connection is still processing some motion events.
104// This will help with the case when a user touched a button that opens a new window,
105// and gives us the chance to dispatch the key to this new window.
106constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000109constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
110
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111// Event log tags. See EventLogTags.logtags for reference
112constexpr int LOGTAG_INPUT_INTERACTION = 62000;
113constexpr int LOGTAG_INPUT_FOCUS = 62001;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115static inline nsecs_t now() {
116 return systemTime(SYSTEM_TIME_MONOTONIC);
117}
118
119static inline const char* toString(bool value) {
120 return value ? "true" : "false";
121}
122
123static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700124 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
125 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126}
127
128static bool isValidKeyAction(int32_t action) {
129 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 case AKEY_EVENT_ACTION_DOWN:
131 case AKEY_EVENT_ACTION_UP:
132 return true;
133 default:
134 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 }
136}
137
138static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 ALOGE("Key event has invalid action code 0x%x", action);
141 return false;
142 }
143 return true;
144}
145
Michael Wright7b159c92015-05-14 14:48:03 +0100146static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700148 case AMOTION_EVENT_ACTION_DOWN:
149 case AMOTION_EVENT_ACTION_UP:
150 case AMOTION_EVENT_ACTION_CANCEL:
151 case AMOTION_EVENT_ACTION_MOVE:
152 case AMOTION_EVENT_ACTION_OUTSIDE:
153 case AMOTION_EVENT_ACTION_HOVER_ENTER:
154 case AMOTION_EVENT_ACTION_HOVER_MOVE:
155 case AMOTION_EVENT_ACTION_HOVER_EXIT:
156 case AMOTION_EVENT_ACTION_SCROLL:
157 return true;
158 case AMOTION_EVENT_ACTION_POINTER_DOWN:
159 case AMOTION_EVENT_ACTION_POINTER_UP: {
160 int32_t index = getMotionEventActionPointerIndex(action);
161 return index >= 0 && index < pointerCount;
162 }
163 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
164 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
165 return actionButton != 0;
166 default:
167 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 }
169}
170
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500171static int64_t millis(std::chrono::nanoseconds t) {
172 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
173}
174
Michael Wright7b159c92015-05-14 14:48:03 +0100175static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 const PointerProperties* pointerProperties) {
177 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 ALOGE("Motion event has invalid action code 0x%x", action);
179 return false;
180 }
181 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000182 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return false;
185 }
186 BitSet32 pointerIdBits;
187 for (size_t i = 0; i < pointerCount; i++) {
188 int32_t id = pointerProperties[i].id;
189 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
191 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 return false;
193 }
194 if (pointerIdBits.hasBit(id)) {
195 ALOGE("Motion event has duplicate pointer id %d", id);
196 return false;
197 }
198 pointerIdBits.markBit(id);
199 }
200 return true;
201}
202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 return;
207 }
208
209 bool first = true;
210 Region::const_iterator cur = region.begin();
211 Region::const_iterator const tail = region.end();
212 while (cur != tail) {
213 if (first) {
214 first = false;
215 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800216 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 cur++;
220 }
221}
222
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500223static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
224 constexpr size_t maxEntries = 50; // max events to print
225 constexpr size_t skipBegin = maxEntries / 2;
226 const size_t skipEnd = queue.size() - maxEntries / 2;
227 // skip from maxEntries / 2 ... size() - maxEntries/2
228 // only print from 0 .. skipBegin and then from skipEnd .. size()
229
230 std::string dump;
231 for (size_t i = 0; i < queue.size(); i++) {
232 const DispatchEntry& entry = *queue[i];
233 if (i >= skipBegin && i < skipEnd) {
234 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
235 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
236 continue;
237 }
238 dump.append(INDENT4);
239 dump += entry.eventEntry->getDescription();
240 dump += StringPrintf(", seq=%" PRIu32
241 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
242 entry.seq, entry.targetFlags, entry.resolvedAction,
243 ns2ms(currentTime - entry.eventEntry->eventTime));
244 if (entry.deliveryTime != 0) {
245 // This entry was delivered, so add information on how long we've been waiting
246 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
247 }
248 dump.append("\n");
249 }
250 return dump;
251}
252
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700253/**
254 * Find the entry in std::unordered_map by key, and return it.
255 * If the entry is not found, return a default constructed entry.
256 *
257 * Useful when the entries are vectors, since an empty vector will be returned
258 * if the entry is not found.
259 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
260 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700261template <typename K, typename V>
262static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700263 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700264 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800265}
266
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700267/**
268 * Find the entry in std::unordered_map by value, and remove it.
269 * If more than one entry has the same value, then all matching
270 * key-value pairs will be removed.
271 *
272 * Return true if at least one value has been removed.
273 */
274template <typename K, typename V>
275static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
276 bool removed = false;
277 for (auto it = map.begin(); it != map.end();) {
278 if (it->second == value) {
279 it = map.erase(it);
280 removed = true;
281 } else {
282 it++;
283 }
284 }
285 return removed;
286}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800287
Vishnu Nair958da932020-08-21 17:12:37 -0700288/**
289 * Find the entry in std::unordered_map by key and return the value as an optional.
290 */
291template <typename K, typename V>
292static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
293 auto it = map.find(key);
294 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
295}
296
chaviwaf87b3e2019-10-01 16:59:28 -0700297static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
298 if (first == second) {
299 return true;
300 }
301
302 if (first == nullptr || second == nullptr) {
303 return false;
304 }
305
306 return first->getToken() == second->getToken();
307}
308
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800309static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
310 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
311}
312
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000313static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
314 EventEntry* eventEntry,
315 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 if (inputTarget.useDefaultPointerTransform()) {
317 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 inputTargetFlags, transform,
320 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321 }
322
323 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
324 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
325
326 PointerCoords pointerCoords[motionEntry.pointerCount];
327
328 // Use the first pointer information to normalize all other pointers. This could be any pointer
329 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700330 // uses the transform for the normalized pointer.
331 const ui::Transform& firstPointerTransform =
332 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
333 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000334
335 // Iterate through all pointers in the event to normalize against the first.
336 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
337 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
338 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000340
341 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700342 // First, apply the current pointer's transform to update the coordinates into
343 // window space.
344 pointerCoords[pointerIndex].transform(currTransform);
345 // Next, apply the inverse transform of the normalized coordinates so the
346 // current coordinates are transformed into the normalized coordinate space.
347 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348 }
349
350 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800351 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
353 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
354 motionEntry.metaState, motionEntry.buttonState,
355 motionEntry.classification, motionEntry.edgeFlags,
356 motionEntry.xPrecision, motionEntry.yPrecision,
357 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
358 motionEntry.downTime, motionEntry.pointerCount,
359 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
360 0 /* yOffset */);
361
362 if (motionEntry.injectionState) {
363 combinedMotionEntry->injectionState = motionEntry.injectionState;
364 combinedMotionEntry->injectionState->refCount += 1;
365 }
366
367 std::unique_ptr<DispatchEntry> dispatchEntry =
368 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 inputTargetFlags, firstPointerTransform,
370 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000371 combinedMotionEntry->release();
372 return dispatchEntry;
373}
374
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700375static void addGestureMonitors(const std::vector<Monitor>& monitors,
376 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
377 float yOffset = 0) {
378 if (monitors.empty()) {
379 return;
380 }
381 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
382 for (const Monitor& monitor : monitors) {
383 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
384 }
385}
386
Garfield Tan15601662020-09-22 15:32:38 -0700387static status_t openInputChannelPair(const std::string& name,
388 std::shared_ptr<InputChannel>& serverChannel,
389 std::unique_ptr<InputChannel>& clientChannel) {
390 std::unique_ptr<InputChannel> uniqueServerChannel;
391 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
392
393 serverChannel = std::move(uniqueServerChannel);
394 return result;
395}
396
Vishnu Nair958da932020-08-21 17:12:37 -0700397const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
398 switch (result) {
399 case InputDispatcher::FocusResult::OK:
400 return "Ok";
401 case InputDispatcher::FocusResult::NO_WINDOW:
402 return "Window not found";
403 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
404 return "Window not focusable";
405 case InputDispatcher::FocusResult::NOT_VISIBLE:
406 return "Window not visible";
407 }
408}
409
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500410template <typename T>
411static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
412 if (lhs == nullptr && rhs == nullptr) {
413 return true;
414 }
415 if (lhs == nullptr || rhs == nullptr) {
416 return false;
417 }
418 return *lhs == *rhs;
419}
420
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421// --- InputDispatcher ---
422
Garfield Tan00f511d2019-06-12 16:55:40 -0700423InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
424 : mPolicy(policy),
425 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700426 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800427 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700428 mAppSwitchSawKeyDown(false),
429 mAppSwitchDueTime(LONG_LONG_MAX),
430 mNextUnblockedEvent(nullptr),
431 mDispatchEnabled(false),
432 mDispatchFrozen(false),
433 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800434 // mInTouchMode will be initialized by the WindowManager to the default device config.
435 // To avoid leaking stack in case that call never comes, and for tests,
436 // initialize it here anyways.
437 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100438 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700439 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800441 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442
Yi Kong9b14ac62018-07-17 13:48:38 -0700443 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444
445 policy->getDispatcherConfiguration(&mConfig);
446}
447
448InputDispatcher::~InputDispatcher() {
449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451
452 resetKeyRepeatLocked();
453 releasePendingEventLocked();
454 drainInboundQueueLocked();
455 }
456
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700457 while (!mConnectionsByFd.empty()) {
458 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700459 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 }
461}
462
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700463status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700464 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700465 return ALREADY_EXISTS;
466 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700467 mThread = std::make_unique<InputThread>(
468 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
469 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700470}
471
472status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700473 if (mThread && mThread->isCallingThread()) {
474 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700475 return INVALID_OPERATION;
476 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700477 mThread.reset();
478 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700479}
480
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481void InputDispatcher::dispatchOnce() {
482 nsecs_t nextWakeupTime = LONG_LONG_MAX;
483 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800484 std::scoped_lock _l(mLock);
485 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486
487 // Run a dispatch loop if there are no pending commands.
488 // The dispatch loop might enqueue commands to run afterwards.
489 if (!haveCommandsLocked()) {
490 dispatchOnceInnerLocked(&nextWakeupTime);
491 }
492
493 // Run all pending commands if there are any.
494 // If any commands were run then force the next poll to wake up immediately.
495 if (runCommandsLockedInterruptible()) {
496 nextWakeupTime = LONG_LONG_MIN;
497 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700499 // If we are still waiting for ack on some events,
500 // we might have to wake up earlier to check if an app is anr'ing.
501 const nsecs_t nextAnrCheck = processAnrsLocked();
502 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
503
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800504 // We are about to enter an infinitely long sleep, because we have no commands or
505 // pending or queued events
506 if (nextWakeupTime == LONG_LONG_MAX) {
507 mDispatcherEnteredIdle.notify_all();
508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 } // release lock
510
511 // Wait for callback or timeout or wake. (make sure we round up, not down)
512 nsecs_t currentTime = now();
513 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
514 mLooper->pollOnce(timeoutMillis);
515}
516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700517/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500518 * Raise ANR if there is no focused window.
519 * Before the ANR is raised, do a final state check:
520 * 1. The currently focused application must be the same one we are waiting for.
521 * 2. Ensure we still don't have a focused window.
522 */
523void InputDispatcher::processNoFocusedWindowAnrLocked() {
524 // Check if the application that we are waiting for is still focused.
525 std::shared_ptr<InputApplicationHandle> focusedApplication =
526 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
527 if (focusedApplication == nullptr ||
528 focusedApplication->getApplicationToken() !=
529 mAwaitedFocusedApplication->getApplicationToken()) {
530 // Unexpected because we should have reset the ANR timer when focused application changed
531 ALOGE("Waited for a focused window, but focused application has already changed to %s",
532 focusedApplication->getName().c_str());
533 return; // The focused application has changed.
534 }
535
536 const sp<InputWindowHandle>& focusedWindowHandle =
537 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
538 if (focusedWindowHandle != nullptr) {
539 return; // We now have a focused window. No need for ANR.
540 }
541 onAnrLocked(mAwaitedFocusedApplication);
542}
543
544/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700545 * Check if any of the connections' wait queues have events that are too old.
546 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
547 * Return the time at which we should wake up next.
548 */
549nsecs_t InputDispatcher::processAnrsLocked() {
550 const nsecs_t currentTime = now();
551 nsecs_t nextAnrCheck = LONG_LONG_MAX;
552 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
553 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
554 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500555 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700556 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500557 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700558 return LONG_LONG_MIN;
559 } else {
560 // Keep waiting
561 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
562 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
563 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
564 }
565 }
566
567 // Check if any connection ANRs are due
568 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
569 if (currentTime < nextAnrCheck) { // most likely scenario
570 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
571 }
572
573 // If we reached here, we have an unresponsive connection.
574 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
575 if (connection == nullptr) {
576 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
577 return nextAnrCheck;
578 }
579 connection->responsive = false;
580 // Stop waking up for this unresponsive connection
581 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500582 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700583 return LONG_LONG_MIN;
584}
585
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500586std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700587 sp<InputWindowHandle> window = getWindowHandleLocked(token);
588 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500589 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500591 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700592}
593
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
595 nsecs_t currentTime = now();
596
Jeff Browndc5992e2014-04-11 01:27:26 -0700597 // Reset the key repeat timer whenever normal dispatch is suspended while the
598 // device is in a non-interactive state. This is to ensure that we abort a key
599 // repeat if the device is just coming out of sleep.
600 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 resetKeyRepeatLocked();
602 }
603
604 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
605 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100606 if (DEBUG_FOCUS) {
607 ALOGD("Dispatch frozen. Waiting some more.");
608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 return;
610 }
611
612 // Optimize latency of app switches.
613 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
614 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
615 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
616 if (mAppSwitchDueTime < *nextWakeupTime) {
617 *nextWakeupTime = mAppSwitchDueTime;
618 }
619
620 // Ready to start a new event.
621 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700622 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700623 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 if (isAppSwitchDue) {
625 // The inbound queue is empty so the app switch key we were waiting
626 // for will never arrive. Stop waiting for it.
627 resetPendingAppSwitchLocked(false);
628 isAppSwitchDue = false;
629 }
630
631 // Synthesize a key repeat if appropriate.
632 if (mKeyRepeatState.lastKeyEntry) {
633 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
634 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
635 } else {
636 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
637 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
638 }
639 }
640 }
641
642 // Nothing to do if there is no pending event.
643 if (!mPendingEvent) {
644 return;
645 }
646 } else {
647 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700648 mPendingEvent = mInboundQueue.front();
649 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 traceInboundQueueLengthLocked();
651 }
652
653 // Poke user activity for this event.
654 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700655 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 }
658
659 // Now we have an event to dispatch.
660 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700661 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 }
669
670 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700671 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 }
673
674 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700675 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 ConfigurationChangedEntry* typedEntry =
677 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
678 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 break;
681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700683 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
685 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700686 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700687 break;
688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100690 case EventEntry::Type::FOCUS: {
691 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
692 dispatchFocusLocked(currentTime, typedEntry);
693 done = true;
694 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
695 break;
696 }
697
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700698 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700699 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
700 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700701 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700702 resetPendingAppSwitchLocked(true);
703 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 } else if (dropReason == DropReason::NOT_DROPPED) {
705 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700706 }
707 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700708 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700709 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
712 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 }
714 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
715 break;
716 }
717
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700718 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700719 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
721 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700723 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700724 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700726 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
727 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 }
729 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
730 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
733
734 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700735 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700736 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
Michael Wright3a981722015-06-10 15:26:13 +0100738 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
740 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700741 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 }
743}
744
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700745/**
746 * Return true if the events preceding this incoming motion event should be dropped
747 * Return false otherwise (the default behaviour)
748 */
749bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700750 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700751 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700752
753 // Optimize case where the current application is unresponsive and the user
754 // decides to touch a window in a different application.
755 // If the application takes too long to catch up then we drop all events preceding
756 // the touch into the other window.
757 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700758 int32_t displayId = motionEntry.displayId;
759 int32_t x = static_cast<int32_t>(
760 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
761 int32_t y = static_cast<int32_t>(
762 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
763 sp<InputWindowHandle> touchedWindowHandle =
764 findTouchedWindowAtLocked(displayId, x, y, nullptr);
765 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700766 touchedWindowHandle->getApplicationToken() !=
767 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700768 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700769 ALOGI("Pruning input queue because user touched a different application while waiting "
770 "for %s",
771 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700772 return true;
773 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774
775 // Alternatively, maybe there's a gesture monitor that could handle this event
776 std::vector<TouchedMonitor> gestureMonitors =
777 findTouchedGestureMonitorsLocked(displayId, {});
778 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
779 sp<Connection> connection =
780 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000781 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700782 // This monitor could take more input. Drop all events preceding this
783 // event, so that gesture monitor could get a chance to receive the stream
784 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
785 "responsive gesture monitor that may handle the event",
786 mAwaitedFocusedApplication->getName().c_str());
787 return true;
788 }
789 }
790 }
791
792 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
793 // yet been processed by some connections, the dispatcher will wait for these motion
794 // events to be processed before dispatching the key event. This is because these motion events
795 // may cause a new window to be launched, which the user might expect to receive focus.
796 // To prevent waiting forever for such events, just send the key to the currently focused window
797 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
798 ALOGD("Received a new pointer down event, stop waiting for events to process and "
799 "just send the pending key event to the focused window.");
800 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700801 }
802 return false;
803}
804
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700806 bool needWake = mInboundQueue.empty();
807 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 traceInboundQueueLengthLocked();
809
810 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 // Optimize app switch latency.
813 // If the application takes too long to catch up then we drop all events preceding
814 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700815 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700817 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700819 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700824 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 mAppSwitchSawKeyDown = false;
826 needWake = true;
827 }
828 }
829 }
830 break;
831 }
832
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700833 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700834 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
835 mNextUnblockedEvent = entry;
836 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100840 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700841 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
842 break;
843 }
844 case EventEntry::Type::CONFIGURATION_CHANGED:
845 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700846 // nothing to do
847 break;
848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850
851 return needWake;
852}
853
854void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
855 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700856 mRecentQueue.push_back(entry);
857 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
858 mRecentQueue.front()->release();
859 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 }
861}
862
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700864 int32_t y, TouchState* touchState,
865 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700867 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
868 LOG_ALWAYS_FATAL(
869 "Must provide a valid touch state if adding portal windows or outside targets");
870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700872 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800873 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 const InputWindowInfo* windowInfo = windowHandle->getInfo();
875 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100876 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877
878 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100879 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
880 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
881 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800883 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 if (portalToDisplayId != ADISPLAY_ID_NONE &&
885 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800886 if (addPortalWindows) {
887 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700888 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800889 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700890 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 // Found window.
894 return windowHandle;
895 }
896 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800897
Michael Wright44753b12020-07-08 13:48:11 +0100898 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700899 touchState->addOrUpdateWindow(windowHandle,
900 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
901 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907}
908
Garfield Tane84e6f92019-08-29 17:28:41 -0700909std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700910 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000911 std::vector<TouchedMonitor> touchedMonitors;
912
913 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
914 addGestureMonitors(monitors, touchedMonitors);
915 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
916 const InputWindowInfo* windowInfo = portalWindow->getInfo();
917 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
919 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000920 }
921 return touchedMonitors;
922}
923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700924void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 const char* reason;
926 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700927 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 reason = "inbound event was dropped because the policy consumed it";
932 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700933 case DropReason::DISABLED:
934 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 ALOGI("Dropped event because input dispatch is disabled.");
936 }
937 reason = "inbound event was dropped because input dispatch is disabled";
938 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700939 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 ALOGI("Dropped event because of pending overdue app switch.");
941 reason = "inbound event was dropped because of pending overdue app switch";
942 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700943 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 ALOGI("Dropped event because the current application is not responding and the user "
945 "has started interacting with a different application.");
946 reason = "inbound event was dropped because the current application is not responding "
947 "and the user has started interacting with a different application";
948 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700949 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 ALOGI("Dropped event because it is stale.");
951 reason = "inbound event was dropped because it is stale";
952 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 case DropReason::NOT_DROPPED: {
954 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700959 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700960 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
962 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700965 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700966 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
967 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
969 synthesizeCancelationEventsForAllConnectionsLocked(options);
970 } else {
971 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
972 synthesizeCancelationEventsForAllConnectionsLocked(options);
973 }
974 break;
975 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100976 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700977 case EventEntry::Type::CONFIGURATION_CHANGED:
978 case EventEntry::Type::DEVICE_RESET: {
979 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
980 break;
981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983}
984
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800985static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
987 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988}
989
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700990bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
991 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
992 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
993 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994}
995
996bool InputDispatcher::isAppSwitchPendingLocked() {
997 return mAppSwitchDueTime != LONG_LONG_MAX;
998}
999
1000void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1001 mAppSwitchDueTime = LONG_LONG_MAX;
1002
1003#if DEBUG_APP_SWITCH
1004 if (handled) {
1005 ALOGD("App switch has arrived.");
1006 } else {
1007 ALOGD("App switch was abandoned.");
1008 }
1009#endif
1010}
1011
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001013 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014}
1015
1016bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001017 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 return false;
1019 }
1020
1021 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001022 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001023 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001025 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
1027 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001028 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 return true;
1030}
1031
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001032void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1033 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034}
1035
1036void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001037 while (!mInboundQueue.empty()) {
1038 EventEntry* entry = mInboundQueue.front();
1039 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 releaseInboundEventLocked(entry);
1041 }
1042 traceInboundQueueLengthLocked();
1043}
1044
1045void InputDispatcher::releasePendingEventLocked() {
1046 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001048 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050}
1051
1052void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1053 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001054 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055#if DEBUG_DISPATCH_CYCLE
1056 ALOGD("Injected inbound event was dropped.");
1057#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001058 setInjectionResult(entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 addRecentEventLocked(entry);
1064 entry->release();
1065}
1066
1067void InputDispatcher::resetKeyRepeatLocked() {
1068 if (mKeyRepeatState.lastKeyEntry) {
1069 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072}
1073
Garfield Tane84e6f92019-08-29 17:28:41 -07001074KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1076
1077 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001078 uint32_t policyFlags = entry->policyFlags &
1079 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (entry->refCount == 1) {
1081 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001082 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 entry->eventTime = currentTime;
1084 entry->policyFlags = policyFlags;
1085 entry->repeatCount += 1;
1086 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001088 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001089 entry->displayId, policyFlags, entry->action, entry->flags,
1090 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092
1093 mKeyRepeatState.lastKeyEntry = newEntry;
1094 entry->release();
1095
1096 entry = newEntry;
1097 }
1098 entry->syntheticRepeat = true;
1099
1100 // Increment reference count since we keep a reference to the event in
1101 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1102 entry->refCount += 1;
1103
1104 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1105 return entry;
1106}
1107
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1109 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001111 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#endif
1113
1114 // Reset key repeating in case a keyboard device was added or removed or something.
1115 resetKeyRepeatLocked();
1116
1117 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001118 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1119 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001121 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 return true;
1123}
1124
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001127 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129#endif
1130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 options.deviceId = entry->deviceId;
1133 synthesizeCancelationEventsForAllConnectionsLocked(options);
1134 return true;
1135}
1136
Vishnu Nairad321cd2020-08-20 16:40:21 -07001137void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001138 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001139 if (mPendingEvent != nullptr) {
1140 // Move the pending event to the front of the queue. This will give the chance
1141 // for the pending event to get dispatched to the newly focused window
1142 mInboundQueue.push_front(mPendingEvent);
1143 mPendingEvent = nullptr;
1144 }
1145
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001146 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001147 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001148
1149 // This event should go to the front of the queue, but behind all other focus events
1150 // Find the last focus event, and insert right after it
1151 std::deque<EventEntry*>::reverse_iterator it =
1152 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1153 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1154
1155 // Maintain the order of focus events. Insert the entry after all other focus events.
1156 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001157}
1158
1159void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001160 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001161 if (channel == nullptr) {
1162 return; // Window has gone away
1163 }
1164 InputTarget target;
1165 target.inputChannel = channel;
1166 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1167 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001168 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1169 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001170 std::string reason = std::string("reason=").append(entry->reason);
1171 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 dispatchEventLocked(currentTime, entry, {target});
1173}
1174
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 if (!entry->dispatchInProgress) {
1179 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1180 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1181 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1182 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001183 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 // We have seen two identical key downs in a row which indicates that the device
1185 // driver is automatically generating key repeats itself. We take note of the
1186 // repeat here, but we disable our own next key repeat timer since it is clear that
1187 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001188 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1189 // Make sure we don't get key down from a different device. If a different
1190 // device Id has same key pressed down, the new device Id will replace the
1191 // current one to hold the key repeat with repeat count reset.
1192 // In the future when got a KEY_UP on the device id, drop it and do not
1193 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1195 resetKeyRepeatLocked();
1196 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1197 } else {
1198 // Not a repeat. Save key down state in case we do see a repeat later.
1199 resetKeyRepeatLocked();
1200 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1201 }
1202 mKeyRepeatState.lastKeyEntry = entry;
1203 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001204 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1205 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1206 // The stale device releases the key, reset staleDeviceId.
1207#if DEBUG_INBOUND_EVENT_DETAILS
1208 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1209#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 resetKeyRepeatLocked();
1212 }
1213
1214 if (entry->repeatCount == 1) {
1215 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1216 } else {
1217 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1218 }
1219
1220 entry->dispatchInProgress = true;
1221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001222 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224
1225 // Handle case where the policy asked us to try again later last time.
1226 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1227 if (currentTime < entry->interceptKeyWakeupTime) {
1228 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1229 *nextWakeupTime = entry->interceptKeyWakeupTime;
1230 }
1231 return false; // wait until next wakeup
1232 }
1233 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1234 entry->interceptKeyWakeupTime = 0;
1235 }
1236
1237 // Give the policy a chance to intercept the key.
1238 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1239 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001240 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001241 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001242 sp<IBinder> focusedWindowToken =
1243 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1244 if (focusedWindowToken != nullptr) {
1245 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
1247 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001248 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 entry->refCount += 1;
1250 return false; // wait for the command to run
1251 } else {
1252 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1253 }
1254 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001255 if (*dropReason == DropReason::NOT_DROPPED) {
1256 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
1258 }
1259
1260 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001261 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001263 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1264 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001265 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 return true;
1267 }
1268
1269 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001270 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001272 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001273 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 return false;
1275 }
1276
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001277 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001278 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
1285 // Dispatch the key.
1286 dispatchEventLocked(currentTime, entry, inputTargets);
1287 return true;
1288}
1289
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001290void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001292 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1294 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1296 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1297 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298#endif
1299}
1300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1302 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001303 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 entry->dispatchInProgress = true;
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 }
1310
1311 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001312 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001314 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1315 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 return true;
1317 }
1318
1319 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1320
1321 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001322 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323
1324 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001325 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 if (isPointerEvent) {
1327 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001329 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 } else {
1332 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001333 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001336 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 return false;
1338 }
1339
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001340 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001341 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001342 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1343 return true;
1344 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001345 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001346 CancelationOptions::Mode mode(isPointerEvent
1347 ? CancelationOptions::CANCEL_POINTER_EVENTS
1348 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1349 CancelationOptions options(mode, "input event injection failed");
1350 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 return true;
1352 }
1353
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001354 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001355 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001357 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001358 std::unordered_map<int32_t, TouchState>::iterator it =
1359 mTouchStatesByDisplay.find(entry->displayId);
1360 if (it != mTouchStatesByDisplay.end()) {
1361 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001362 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001363 // The event has gone through these portal windows, so we add monitoring targets of
1364 // the corresponding displays as well.
1365 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001366 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001367 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001369 }
1370 }
1371 }
1372 }
1373
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 // Dispatch the motion.
1375 if (conflictingPointerActions) {
1376 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001377 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 synthesizeCancelationEventsForAllConnectionsLocked(options);
1379 }
1380 dispatchEventLocked(currentTime, entry, inputTargets);
1381 return true;
1382}
1383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001384void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001386 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 ", policyFlags=0x%x, "
1388 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1389 "metaState=0x%x, buttonState=0x%x,"
1390 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1392 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1393 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 "x=%f, y=%f, pressure=%f, size=%f, "
1398 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1399 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1401 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1402 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1403 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1404 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1405 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1406 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1407 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1408 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1409 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 }
1411#endif
1412}
1413
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1415 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001416 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417#if DEBUG_DISPATCH_CYCLE
1418 ALOGD("dispatchEventToCurrentInputTargets");
1419#endif
1420
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001421 updateInteractionTokensLocked(*eventEntry, inputTargets);
1422
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1424
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001425 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001427 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001428 sp<Connection> connection =
1429 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001430 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001431 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001433 if (DEBUG_FOCUS) {
1434 ALOGD("Dropping event delivery to target with channel '%s' because it "
1435 "is no longer registered with the input dispatcher.",
1436 inputTarget.inputChannel->getName().c_str());
1437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
1439 }
1440}
1441
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001442void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1443 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1444 // If the policy decides to close the app, we will get a channel removal event via
1445 // unregisterInputChannel, and will clean up the connection that way. We are already not
1446 // sending new pointers to the connection when it blocked, but focused events will continue to
1447 // pile up.
1448 ALOGW("Canceling events for %s because it is unresponsive",
1449 connection->inputChannel->getName().c_str());
1450 if (connection->status == Connection::STATUS_NORMAL) {
1451 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1452 "application not responding");
1453 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455}
1456
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001457void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001458 if (DEBUG_FOCUS) {
1459 ALOGD("Resetting ANR timeouts.");
1460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
1462 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001463 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001464 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465}
1466
Tiger Huang721e26f2018-07-24 22:26:19 +08001467/**
1468 * Get the display id that the given event should go to. If this event specifies a valid display id,
1469 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1470 * Focused display is the display that the user most recently interacted with.
1471 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001472int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001473 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001474 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001475 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1477 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 break;
1479 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001480 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1482 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 break;
1484 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001485 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001486 case EventEntry::Type::CONFIGURATION_CHANGED:
1487 case EventEntry::Type::DEVICE_RESET: {
1488 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001489 return ADISPLAY_ID_NONE;
1490 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001491 }
1492 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1493}
1494
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001495bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1496 const char* focusedWindowName) {
1497 if (mAnrTracker.empty()) {
1498 // already processed all events that we waited for
1499 mKeyIsWaitingForEventsTimeout = std::nullopt;
1500 return false;
1501 }
1502
1503 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1504 // Start the timer
1505 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1506 "focus to change",
1507 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001508 mKeyIsWaitingForEventsTimeout = currentTime +
1509 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1510 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001511 return true;
1512 }
1513
1514 // We still have pending events, and already started the timer
1515 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1516 return true; // Still waiting
1517 }
1518
1519 // Waited too long, and some connection still hasn't processed all motions
1520 // Just send the key to the focused window
1521 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1522 focusedWindowName);
1523 mKeyIsWaitingForEventsTimeout = std::nullopt;
1524 return false;
1525}
1526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1528 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1529 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001530 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531
Tiger Huang721e26f2018-07-24 22:26:19 +08001532 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001533 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001534 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001535 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1536
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 // If there is no currently focused window and no focused application
1538 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001539 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1540 ALOGI("Dropping %s event because there is no focused window or focused application in "
1541 "display %" PRId32 ".",
1542 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001543 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001546 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1547 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1548 // start interacting with another application via touch (app switch). This code can be removed
1549 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1550 // an app is expected to have a focused window.
1551 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1552 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1553 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001554 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1555 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1556 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001557 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001558 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001559 ALOGW("Waiting because no window has focus but %s may eventually add a "
1560 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001561 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001562 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001564 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1565 // Already raised ANR. Drop the event
1566 ALOGE("Dropping %s event because there is no focused window",
1567 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001568 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001569 } else {
1570 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001572 }
1573 }
1574
1575 // we have a valid, non-null focused window
1576 resetNoFocusedWindowTimeoutLocked();
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001579 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001580 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001583 if (focusedWindowHandle->getInfo()->paused) {
1584 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001586 }
1587
1588 // If the event is a key event, then we must wait for all previous events to
1589 // complete before delivering it because previous events may have the
1590 // side-effect of transferring focus to a different window and we want to
1591 // ensure that the following keys are sent to the new window.
1592 //
1593 // Suppose the user touches a button in a window then immediately presses "A".
1594 // If the button causes a pop-up window to appear then we want to ensure that
1595 // the "A" key is delivered to the new pop-up window. This is because users
1596 // often anticipate pending UI changes when typing on a keyboard.
1597 // To obtain this behavior, we must serialize key events with respect to all
1598 // prior input events.
1599 if (entry.type == EventEntry::Type::KEY) {
1600 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1601 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001602 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605
1606 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001607 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1609 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610
1611 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613}
1614
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001615/**
1616 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1617 * that are currently unresponsive.
1618 */
1619std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1620 const std::vector<TouchedMonitor>& monitors) const {
1621 std::vector<TouchedMonitor> responsiveMonitors;
1622 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1623 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1624 sp<Connection> connection = getConnectionLocked(
1625 monitor.monitor.inputChannel->getConnectionToken());
1626 if (connection == nullptr) {
1627 ALOGE("Could not find connection for monitor %s",
1628 monitor.monitor.inputChannel->getName().c_str());
1629 return false;
1630 }
1631 if (!connection->responsive) {
1632 ALOGW("Unresponsive monitor %s will not get the new gesture",
1633 connection->inputChannel->getName().c_str());
1634 return false;
1635 }
1636 return true;
1637 });
1638 return responsiveMonitors;
1639}
1640
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001641InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1642 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1643 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001644 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 enum InjectionPermission {
1646 INJECTION_PERMISSION_UNKNOWN,
1647 INJECTION_PERMISSION_GRANTED,
1648 INJECTION_PERMISSION_DENIED
1649 };
1650
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 // For security reasons, we defer updating the touch state until we are sure that
1652 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 int32_t displayId = entry.displayId;
1654 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1656
1657 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001660 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1661 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001663 // Copy current touch state into tempTouchState.
1664 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1665 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001666 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001667 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001668 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1669 mTouchStatesByDisplay.find(displayId);
1670 if (oldStateIt != mTouchStatesByDisplay.end()) {
1671 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001672 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001673 }
1674
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001675 bool isSplit = tempTouchState.split;
1676 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1677 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1678 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001679 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1680 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1681 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1682 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1683 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001684 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 bool wrongDevice = false;
1686 if (newGesture) {
1687 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001688 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001689 ALOGI("Dropping event because a pointer for a different device is already down "
1690 "in display %" PRId32,
1691 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001692 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001693 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 switchedDevice = false;
1695 wrongDevice = true;
1696 goto Failed;
1697 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001698 tempTouchState.reset();
1699 tempTouchState.down = down;
1700 tempTouchState.deviceId = entry.deviceId;
1701 tempTouchState.source = entry.source;
1702 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001704 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001705 ALOGI("Dropping move event because a pointer for a different device is already active "
1706 "in display %" PRId32,
1707 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001708 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001709 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001710 switchedDevice = false;
1711 wrongDevice = true;
1712 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714
1715 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1716 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1717
Garfield Tan00f511d2019-06-12 16:55:40 -07001718 int32_t x;
1719 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001721 // Always dispatch mouse events to cursor position.
1722 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001723 x = int32_t(entry.xCursorPosition);
1724 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001725 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001726 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1727 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001728 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001730 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001731 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1732 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001733
1734 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001735 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001739 if (newTouchedWindowHandle != nullptr &&
1740 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001741 // New window supports splitting, but we should never split mouse events.
1742 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 } else if (isSplit) {
1744 // New window does not support splitting but we have already split events.
1745 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001746 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748
1749 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001750 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001752 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001753 }
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1756 ALOGI("Not sending touch event to %s because it is paused",
1757 newTouchedWindowHandle->getName().c_str());
1758 newTouchedWindowHandle = nullptr;
1759 }
1760
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001761 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001762 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001763 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1764 if (!isResponsive) {
1765 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1767 newTouchedWindowHandle = nullptr;
1768 }
1769 }
1770
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001771 // Drop events that can't be trusted due to occlusion
1772 if (newTouchedWindowHandle != nullptr &&
1773 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1774 TouchOcclusionInfo occlusionInfo =
1775 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001776 if (!isTouchTrustedLocked(occlusionInfo)) {
1777 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1778 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1779 ALOGW("Dropping untrusted touch event due to %s/%d",
1780 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1781 newTouchedWindowHandle = nullptr;
1782 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001783 }
1784 }
1785
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 // Also don't send the new touch event to unresponsive gesture monitors
1787 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1788
Michael Wright3dd60e22019-03-27 22:06:44 +00001789 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1790 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 "(%d, %d) in display %" PRId32 ".",
1792 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001794 goto Failed;
1795 }
1796
1797 if (newTouchedWindowHandle != nullptr) {
1798 // Set target flags.
1799 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1800 if (isSplit) {
1801 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001803 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1804 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1805 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1806 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1807 }
1808
1809 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001810 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1811 newHoverWindowHandle = nullptr;
1812 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001814 }
1815
1816 // Update the temporary touch state.
1817 BitSet32 pointerIds;
1818 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001820 pointerIds.markBit(pointerId);
1821 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001825 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 } else {
1827 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1828
1829 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001831 if (DEBUG_FOCUS) {
1832 ALOGD("Dropping event because the pointer is not down or we previously "
1833 "dropped the pointer down event in display %" PRId32,
1834 displayId);
1835 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 goto Failed;
1838 }
1839
1840 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001843 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1844 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
1846 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001848 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001849 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1850 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001851 if (DEBUG_FOCUS) {
1852 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1853 oldTouchedWindowHandle->getName().c_str(),
1854 newTouchedWindowHandle->getName().c_str(), displayId);
1855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1858 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1859 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 // Make a slippery entrance into the new window.
1862 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1863 isSplit = true;
1864 }
1865
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001866 int32_t targetFlags =
1867 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 if (isSplit) {
1869 targetFlags |= InputTarget::FLAG_SPLIT;
1870 }
1871 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1872 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1873 }
1874
1875 BitSet32 pointerIds;
1876 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001877 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001879 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
1881 }
1882 }
1883
1884 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001885 // Let the previous window know that the hover sequence is over, unless we already did it
1886 // when dispatching it as is to newTouchedWindowHandle.
1887 if (mLastHoverWindowHandle != nullptr &&
1888 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1889 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890#if DEBUG_HOVER
1891 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1895 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897
Garfield Tandf26e862020-07-01 20:18:19 -07001898 // Let the new window know that the hover sequence is starting, unless we already did it
1899 // when dispatching it as is to newTouchedWindowHandle.
1900 if (newHoverWindowHandle != nullptr &&
1901 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1902 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903#if DEBUG_HOVER
1904 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001905 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1908 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1909 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911 }
1912
1913 // Check permission to inject into all touched foreground windows and ensure there
1914 // is at least one touched foreground window.
1915 {
1916 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1919 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001920 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 injectionPermission = INJECTION_PERMISSION_DENIED;
1923 goto Failed;
1924 }
1925 }
1926 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001927 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001928 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001929 ALOGI("Dropping event because there is no touched foreground window in display "
1930 "%" PRId32 " or gesture monitor to receive it.",
1931 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 goto Failed;
1934 }
1935
1936 // Permission granted to injection into all touched foreground windows.
1937 injectionPermission = INJECTION_PERMISSION_GRANTED;
1938 }
1939
1940 // Check whether windows listening for outside touches are owned by the same UID. If it is
1941 // set the policy flag that we will not reveal coordinate information to this window.
1942 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1943 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001945 if (foregroundWindowHandle) {
1946 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001947 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001948 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1949 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1950 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001951 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1952 InputTarget::FLAG_ZERO_COORDS,
1953 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
1956 }
1957 }
1958 }
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // If this is the first pointer going down and the touched window has a wallpaper
1961 // then also add the touched wallpaper windows so they are locked in for the duration
1962 // of the touch gesture.
1963 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1964 // engine only supports touch events. We would need to add a mechanism similar
1965 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1966 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1967 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001968 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001970 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001971 getWindowHandlesLocked(displayId);
1972 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001975 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001976 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001977 .addOrUpdateWindow(windowHandle,
1978 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1979 InputTarget::
1980 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1981 InputTarget::FLAG_DISPATCH_AS_IS,
1982 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
1984 }
1985 }
1986 }
1987
1988 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
1995
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001997 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001998 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001999 }
2000
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 // Drop the outside or hover touch windows since we will not care about them
2002 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005Failed:
2006 // Check injection permission once and for all.
2007 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002008 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 injectionPermission = INJECTION_PERMISSION_GRANTED;
2010 } else {
2011 injectionPermission = INJECTION_PERMISSION_DENIED;
2012 }
2013 }
2014
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002015 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2016 return injectionResult;
2017 }
2018
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002020 if (!wrongDevice) {
2021 if (switchedDevice) {
2022 if (DEBUG_FOCUS) {
2023 ALOGD("Conflicting pointer actions: Switched to a different device.");
2024 }
2025 *outConflictingPointerActions = true;
2026 }
2027
2028 if (isHoverAction) {
2029 // Started hovering, therefore no longer down.
2030 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002031 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002032 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2033 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 *outConflictingPointerActions = true;
2036 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002037 tempTouchState.reset();
2038 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2039 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2040 tempTouchState.deviceId = entry.deviceId;
2041 tempTouchState.source = entry.source;
2042 tempTouchState.displayId = displayId;
2043 }
2044 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2045 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2046 // All pointers up or canceled.
2047 tempTouchState.reset();
2048 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2049 // First pointer went down.
2050 if (oldState && oldState->down) {
2051 if (DEBUG_FOCUS) {
2052 ALOGD("Conflicting pointer actions: Down received while already down.");
2053 }
2054 *outConflictingPointerActions = true;
2055 }
2056 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2057 // One pointer went up.
2058 if (isSplit) {
2059 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2060 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002062 for (size_t i = 0; i < tempTouchState.windows.size();) {
2063 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2064 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2065 touchedWindow.pointerIds.clearBit(pointerId);
2066 if (touchedWindow.pointerIds.isEmpty()) {
2067 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2068 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002071 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002073 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002074 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002075
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002076 // Save changes unless the action was scroll in which case the temporary touch
2077 // state was only valid for this one action.
2078 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2079 if (tempTouchState.displayId >= 0) {
2080 mTouchStatesByDisplay[displayId] = tempTouchState;
2081 } else {
2082 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002086 // Update hover state.
2087 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 return injectionResult;
2091}
2092
2093void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 int32_t targetFlags, BitSet32 pointerIds,
2095 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002096 std::vector<InputTarget>::iterator it =
2097 std::find_if(inputTargets.begin(), inputTargets.end(),
2098 [&windowHandle](const InputTarget& inputTarget) {
2099 return inputTarget.inputChannel->getConnectionToken() ==
2100 windowHandle->getToken();
2101 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002102
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002103 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002104
2105 if (it == inputTargets.end()) {
2106 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002107 std::shared_ptr<InputChannel> inputChannel =
2108 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002109 if (inputChannel == nullptr) {
2110 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2111 return;
2112 }
2113 inputTarget.inputChannel = inputChannel;
2114 inputTarget.flags = targetFlags;
2115 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2116 inputTargets.push_back(inputTarget);
2117 it = inputTargets.end() - 1;
2118 }
2119
2120 ALOG_ASSERT(it->flags == targetFlags);
2121 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2122
chaviw1ff3d1e2020-07-01 15:53:47 -07002123 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124}
2125
Michael Wright3dd60e22019-03-27 22:06:44 +00002126void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 int32_t displayId, float xOffset,
2128 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002129 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2130 mGlobalMonitorsByDisplay.find(displayId);
2131
2132 if (it != mGlobalMonitorsByDisplay.end()) {
2133 const std::vector<Monitor>& monitors = it->second;
2134 for (const Monitor& monitor : monitors) {
2135 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138}
2139
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2141 float yOffset,
2142 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 InputTarget target;
2144 target.inputChannel = monitor.inputChannel;
2145 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002146 ui::Transform t;
2147 t.set(xOffset, yOffset);
2148 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 inputTargets.push_back(target);
2150}
2151
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 const InjectionState* injectionState) {
2154 if (injectionState &&
2155 (windowHandle == nullptr ||
2156 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2157 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002158 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 "owned by uid %d",
2161 injectionState->injectorPid, injectionState->injectorUid,
2162 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 } else {
2164 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
2167 return false;
2168 }
2169 return true;
2170}
2171
Robert Carrc9bf1d32020-04-13 17:21:08 -07002172/**
2173 * Indicate whether one window handle should be considered as obscuring
2174 * another window handle. We only check a few preconditions. Actually
2175 * checking the bounds is left to the caller.
2176 */
2177static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2178 const sp<InputWindowHandle>& otherHandle) {
2179 // Compare by token so cloned layers aren't counted
2180 if (haveSameToken(windowHandle, otherHandle)) {
2181 return false;
2182 }
2183 auto info = windowHandle->getInfo();
2184 auto otherInfo = otherHandle->getInfo();
2185 if (!otherInfo->visible) {
2186 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002187 } else if (otherInfo->alpha == 0 &&
2188 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2189 // Those act as if they were invisible, so we don't need to flag them.
2190 // We do want to potentially flag touchable windows even if they have 0
2191 // opacity, since they can consume touches and alter the effects of the
2192 // user interaction (eg. apps that rely on
2193 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2194 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2195 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002196 } else if (info->ownerUid == otherInfo->ownerUid) {
2197 // If ownerUid is the same we don't generate occlusion events as there
2198 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002199 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002200 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002201 return false;
2202 } else if (otherInfo->displayId != info->displayId) {
2203 return false;
2204 }
2205 return true;
2206}
2207
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002208/**
2209 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2210 * untrusted, one should check:
2211 *
2212 * 1. If result.hasBlockingOcclusion is true.
2213 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2214 * BLOCK_UNTRUSTED.
2215 *
2216 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2217 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2218 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2219 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2220 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2221 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2222 *
2223 * If neither of those is true, then it means the touch can be allowed.
2224 */
2225InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2226 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2227 int32_t displayId = windowHandle->getInfo()->displayId;
2228 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2229 TouchOcclusionInfo info;
2230 info.hasBlockingOcclusion = false;
2231 info.obscuringOpacity = 0;
2232 info.obscuringUid = -1;
2233 std::map<int32_t, float> opacityByUid;
2234 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2235 if (windowHandle == otherHandle) {
2236 break; // All future windows are below us. Exit early.
2237 }
2238 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2239 if (canBeObscuredBy(windowHandle, otherHandle) &&
2240 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2241 otherInfo->frameContainsPoint(x, y)) {
2242 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2243 // we perform the checks below to see if the touch can be propagated or not based on the
2244 // window's touch occlusion mode
2245 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2246 info.hasBlockingOcclusion = true;
2247 info.obscuringUid = otherInfo->ownerUid;
2248 info.obscuringPackage = otherInfo->packageName;
2249 break;
2250 }
2251 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2252 uint32_t uid = otherInfo->ownerUid;
2253 float opacity =
2254 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2255 // Given windows A and B:
2256 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2257 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2258 opacityByUid[uid] = opacity;
2259 if (opacity > info.obscuringOpacity) {
2260 info.obscuringOpacity = opacity;
2261 info.obscuringUid = uid;
2262 info.obscuringPackage = otherInfo->packageName;
2263 }
2264 }
2265 }
2266 }
2267 return info;
2268}
2269
2270bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2271 if (occlusionInfo.hasBlockingOcclusion) {
2272 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2273 occlusionInfo.obscuringUid);
2274 return false;
2275 }
2276 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2277 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2278 "%.2f, maximum allowed = %.2f)",
2279 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2280 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2281 return false;
2282 }
2283 return true;
2284}
2285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2287 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002289 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002290 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002291 if (windowHandle == otherHandle) {
2292 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002295 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002296 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 return true;
2298 }
2299 }
2300 return false;
2301}
2302
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002303bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2304 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002305 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002306 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002307 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002308 if (windowHandle == otherHandle) {
2309 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002310 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002311 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002312 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002313 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002314 return true;
2315 }
2316 }
2317 return false;
2318}
2319
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002320std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002321 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002323 if (applicationHandle != nullptr) {
2324 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002325 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 } else {
2327 return applicationHandle->getName();
2328 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002329 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002330 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002332 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
2334}
2335
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002337 if (eventEntry.type == EventEntry::Type::FOCUS) {
2338 // Focus events are passed to apps, but do not represent user activity.
2339 return;
2340 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002341 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002342 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002343 if (focusedWindowHandle != nullptr) {
2344 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002345 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002347 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348#endif
2349 return;
2350 }
2351 }
2352
2353 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002354 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002355 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002356 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2357 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 return;
2359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002361 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 eventType = USER_ACTIVITY_EVENT_TOUCH;
2363 }
2364 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002366 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002367 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2368 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 return;
2370 }
2371 eventType = USER_ACTIVITY_EVENT_BUTTON;
2372 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002374 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002375 case EventEntry::Type::CONFIGURATION_CHANGED:
2376 case EventEntry::Type::DEVICE_RESET: {
2377 LOG_ALWAYS_FATAL("%s events are not user activity",
2378 EventEntry::typeToString(eventEntry.type));
2379 break;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002383 std::unique_ptr<CommandEntry> commandEntry =
2384 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002385 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002387 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388}
2389
2390void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002391 const sp<Connection>& connection,
2392 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002393 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002394 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002396 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002397 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002398 ATRACE_NAME(message.c_str());
2399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400#if DEBUG_DISPATCH_CYCLE
2401 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002402 "globalScaleFactor=%f, pointerIds=0x%x %s",
2403 connection->getInputChannelName().c_str(), inputTarget.flags,
2404 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2405 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406#endif
2407
2408 // Skip this event if the connection status is not normal.
2409 // We don't want to enqueue additional outbound events if the connection is broken.
2410 if (connection->status != Connection::STATUS_NORMAL) {
2411#if DEBUG_DISPATCH_CYCLE
2412 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414#endif
2415 return;
2416 }
2417
2418 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002419 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2420 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2421 "Entry type %s should not have FLAG_SPLIT",
2422 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002424 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002425 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002426 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002427 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 if (!splitMotionEntry) {
2429 return; // split event was dropped
2430 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002431 if (DEBUG_FOCUS) {
2432 ALOGD("channel '%s' ~ Split motion event.",
2433 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002434 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002435 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002436 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 splitMotionEntry->release();
2438 return;
2439 }
2440 }
2441
2442 // Not splitting. Enqueue dispatch entries for the event as is.
2443 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2444}
2445
2446void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447 const sp<Connection>& connection,
2448 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002449 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002450 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002452 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002453 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002454 ATRACE_NAME(message.c_str());
2455 }
2456
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002457 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458
2459 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002460 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002462 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002464 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002466 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002468 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002470 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
2473 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002474 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 startDispatchCycleLocked(currentTime, connection);
2476 }
2477}
2478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2480 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002481 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002483 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2485 connection->getInputChannelName().c_str(),
2486 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002487 ATRACE_NAME(message.c_str());
2488 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002489 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 if (!(inputTargetFlags & dispatchMode)) {
2491 return;
2492 }
2493 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2494
2495 // This is a new event.
2496 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002497 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002498 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002500 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2501 // different EventEntry than what was passed in.
2502 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002504 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002505 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002506 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002507 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002508 dispatchEntry->resolvedAction = keyEntry.action;
2509 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2512 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002514 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2515 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 return; // skip the inconsistent event
2518 }
2519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002522 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002523 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002524 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2525 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2526 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2527 static_cast<int32_t>(IdGenerator::Source::OTHER);
2528 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2530 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2531 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2532 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2533 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2534 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2535 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2536 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2537 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2538 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2539 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002540 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002541 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 }
2543 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002544 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2545 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2548 "event",
2549 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002554 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2556 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2557 }
2558 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2559 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2563 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002565 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2566 "event",
2567 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 return; // skip the inconsistent event
2570 }
2571
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002572 dispatchEntry->resolvedEventId =
2573 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2574 ? mIdGenerator.nextId()
2575 : motionEntry.id;
2576 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2577 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2578 ") to MotionEvent(id=0x%" PRIx32 ").",
2579 motionEntry.id, dispatchEntry->resolvedEventId);
2580 ATRACE_NAME(message.c_str());
2581 }
2582
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002583 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002584 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585
2586 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002588 case EventEntry::Type::FOCUS: {
2589 break;
2590 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002591 case EventEntry::Type::CONFIGURATION_CHANGED:
2592 case EventEntry::Type::DEVICE_RESET: {
2593 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002594 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002595 break;
2596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598
2599 // Remember that we are waiting for this dispatch to complete.
2600 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002601 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603
2604 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002605 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002606 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002607}
2608
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002609/**
2610 * This function is purely for debugging. It helps us understand where the user interaction
2611 * was taking place. For example, if user is touching launcher, we will see a log that user
2612 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2613 * We will see both launcher and wallpaper in that list.
2614 * Once the interaction with a particular set of connections starts, no new logs will be printed
2615 * until the set of interacted connections changes.
2616 *
2617 * The following items are skipped, to reduce the logspam:
2618 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2619 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2620 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2621 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2622 * Both of those ACTION_UP events would not be logged
2623 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2624 * will not be logged. This is omitted to reduce the amount of data printed.
2625 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2626 * gesture monitor is the only connection receiving the remainder of the gesture.
2627 */
2628void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2629 const std::vector<InputTarget>& targets) {
2630 // Skip ACTION_UP events, and all events other than keys and motions
2631 if (entry.type == EventEntry::Type::KEY) {
2632 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2633 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2634 return;
2635 }
2636 } else if (entry.type == EventEntry::Type::MOTION) {
2637 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2638 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2639 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2640 return;
2641 }
2642 } else {
2643 return; // Not a key or a motion
2644 }
2645
2646 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2647 std::vector<sp<Connection>> newConnections;
2648 for (const InputTarget& target : targets) {
2649 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2650 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2651 continue; // Skip windows that receive ACTION_OUTSIDE
2652 }
2653
2654 sp<IBinder> token = target.inputChannel->getConnectionToken();
2655 sp<Connection> connection = getConnectionLocked(token);
2656 if (connection == nullptr || connection->monitor) {
2657 continue; // We only need to keep track of the non-monitor connections.
2658 }
2659 newConnectionTokens.insert(std::move(token));
2660 newConnections.emplace_back(connection);
2661 }
2662 if (newConnectionTokens == mInteractionConnectionTokens) {
2663 return; // no change
2664 }
2665 mInteractionConnectionTokens = newConnectionTokens;
2666
2667 std::string windowList;
2668 for (const sp<Connection>& connection : newConnections) {
2669 windowList += connection->getWindowName() + ", ";
2670 }
2671 std::string message = "Interaction with windows: " + windowList;
2672 if (windowList.empty()) {
2673 message += "<none>";
2674 }
2675 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2676}
2677
chaviwfd6d3512019-03-25 13:23:49 -07002678void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002679 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002680 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002681 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2682 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002683 return;
2684 }
2685
Vishnu Nairad321cd2020-08-20 16:40:21 -07002686 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2687 if (focusedToken == token) {
2688 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002689 return;
2690 }
2691
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002692 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2693 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002694 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002695 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696}
2697
2698void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002699 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002700 if (ATRACE_ENABLED()) {
2701 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002703 ATRACE_NAME(message.c_str());
2704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002706 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707#endif
2708
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002709 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2710 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002712 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002713 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002714 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
2716 // Publish the event.
2717 status_t status;
2718 EventEntry* eventEntry = dispatchEntry->eventEntry;
2719 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002720 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002721 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2722 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002725 status =
2726 connection->inputPublisher
2727 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2728 keyEntry->deviceId, keyEntry->source,
2729 keyEntry->displayId, std::move(hmac),
2730 dispatchEntry->resolvedAction,
2731 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2732 keyEntry->scanCode, keyEntry->metaState,
2733 keyEntry->repeatCount, keyEntry->downTime,
2734 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002738 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 PointerCoords scaledCoords[MAX_POINTERS];
2742 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2743
chaviw82357092020-01-28 13:13:06 -08002744 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2746 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2747 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002748 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2750 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002751 // Don't apply window scale here since we don't want scale to affect raw
2752 // coordinates. The scale will be sent back to the client and applied
2753 // later when requesting relative coordinates.
2754 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2755 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756 }
2757 usingCoords = scaledCoords;
2758 }
2759 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 // We don't want the dispatch target to know.
2761 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2762 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2763 scaledCoords[i].clear();
2764 }
2765 usingCoords = scaledCoords;
2766 }
2767 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002768
2769 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770
2771 // Publish the motion event.
2772 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002773 .publishMotionEvent(dispatchEntry->seq,
2774 dispatchEntry->resolvedEventId,
2775 motionEntry->deviceId, motionEntry->source,
2776 motionEntry->displayId, std::move(hmac),
2777 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 motionEntry->actionButton,
2779 dispatchEntry->resolvedFlags,
2780 motionEntry->edgeFlags, motionEntry->metaState,
2781 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002782 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002783 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002784 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785 motionEntry->yPrecision,
2786 motionEntry->xCursorPosition,
2787 motionEntry->yCursorPosition,
2788 motionEntry->downTime, motionEntry->eventTime,
2789 motionEntry->pointerCount,
2790 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002791 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002792 break;
2793 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002794 case EventEntry::Type::FOCUS: {
2795 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2796 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002797 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002798 focusEntry->hasFocus,
2799 mInTouchMode);
2800 break;
2801 }
2802
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002803 case EventEntry::Type::CONFIGURATION_CHANGED:
2804 case EventEntry::Type::DEVICE_RESET: {
2805 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2806 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
2810
2811 // Check the result.
2812 if (status) {
2813 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002814 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 "This is unexpected because the wait queue is empty, so the pipe "
2817 "should be empty and we shouldn't have any problems writing an "
2818 "event to it, status=%d",
2819 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2821 } else {
2822 // Pipe is full and we are waiting for the app to finish process some events
2823 // before sending more events to it.
2824#if DEBUG_DISPATCH_CYCLE
2825 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 "waiting for the application to catch up",
2827 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830 } else {
2831 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 "status=%d",
2833 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2835 }
2836 return;
2837 }
2838
2839 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002840 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2841 connection->outboundQueue.end(),
2842 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002843 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002844 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002845 if (connection->responsive) {
2846 mAnrTracker.insert(dispatchEntry->timeoutTime,
2847 connection->inputChannel->getConnectionToken());
2848 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002849 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
2851}
2852
chaviw09c8d2d2020-08-24 15:48:26 -07002853std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2854 size_t size;
2855 switch (event.type) {
2856 case VerifiedInputEvent::Type::KEY: {
2857 size = sizeof(VerifiedKeyEvent);
2858 break;
2859 }
2860 case VerifiedInputEvent::Type::MOTION: {
2861 size = sizeof(VerifiedMotionEvent);
2862 break;
2863 }
2864 }
2865 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2866 return mHmacKeyManager.sign(start, size);
2867}
2868
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002869const std::array<uint8_t, 32> InputDispatcher::getSignature(
2870 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2871 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2872 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2873 // Only sign events up and down events as the purely move events
2874 // are tied to their up/down counterparts so signing would be redundant.
2875 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2876 verifiedEvent.actionMasked = actionMasked;
2877 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002878 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002879 }
2880 return INVALID_HMAC;
2881}
2882
2883const std::array<uint8_t, 32> InputDispatcher::getSignature(
2884 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2885 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2886 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2887 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002888 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002889}
2890
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 const sp<Connection>& connection, uint32_t seq,
2893 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#if DEBUG_DISPATCH_CYCLE
2895 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897#endif
2898
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 if (connection->status == Connection::STATUS_BROKEN ||
2900 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 return;
2902 }
2903
2904 // Notify other system components and prepare to start the next dispatch cycle.
2905 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2906}
2907
2908void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 const sp<Connection>& connection,
2910 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911#if DEBUG_DISPATCH_CYCLE
2912 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#endif
2915
2916 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002917 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002918 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002919 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002920 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921
2922 // The connection appears to be unrecoverably broken.
2923 // Ignore already broken or zombie connections.
2924 if (connection->status == Connection::STATUS_NORMAL) {
2925 connection->status = Connection::STATUS_BROKEN;
2926
2927 if (notify) {
2928 // Notify other system components.
2929 onDispatchCycleBrokenLocked(currentTime, connection);
2930 }
2931 }
2932}
2933
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002934void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2935 while (!queue.empty()) {
2936 DispatchEntry* dispatchEntry = queue.front();
2937 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002938 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 }
2940}
2941
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002942void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002944 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
2946 delete dispatchEntry;
2947}
2948
2949int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2950 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2951
2952 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002953 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002955 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 "fd=%d, events=0x%x",
2958 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 return 0; // remove the callback
2960 }
2961
2962 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002963 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2965 if (!(events & ALOOPER_EVENT_INPUT)) {
2966 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 "events=0x%x",
2968 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 return 1;
2970 }
2971
2972 nsecs_t currentTime = now();
2973 bool gotOne = false;
2974 status_t status;
2975 for (;;) {
2976 uint32_t seq;
2977 bool handled;
2978 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2979 if (status) {
2980 break;
2981 }
2982 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2983 gotOne = true;
2984 }
2985 if (gotOne) {
2986 d->runCommandsLockedInterruptible();
2987 if (status == WOULD_BLOCK) {
2988 return 1;
2989 }
2990 }
2991
2992 notify = status != DEAD_OBJECT || !connection->monitor;
2993 if (notify) {
2994 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 }
2997 } else {
2998 // Monitor channels are never explicitly unregistered.
2999 // We do it automatically when the remote endpoint is closed so don't warn
3000 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003001 const bool stillHaveWindowHandle =
3002 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3003 nullptr;
3004 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 if (notify) {
3006 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 "events=0x%x",
3008 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
3010 }
3011
Garfield Tan15601662020-09-22 15:32:38 -07003012 // Remove the channel.
3013 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016}
3017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003018void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003020 for (const auto& pair : mConnectionsByFd) {
3021 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 }
3023}
3024
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003025void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003026 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3028 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3029}
3030
3031void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3032 const CancelationOptions& options,
3033 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3034 for (const auto& it : monitorsByDisplay) {
3035 const std::vector<Monitor>& monitors = it.second;
3036 for (const Monitor& monitor : monitors) {
3037 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003038 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003039 }
3040}
3041
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003043 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003044 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003045 if (connection == nullptr) {
3046 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003048
3049 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050}
3051
3052void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3053 const sp<Connection>& connection, const CancelationOptions& options) {
3054 if (connection->status == Connection::STATUS_BROKEN) {
3055 return;
3056 }
3057
3058 nsecs_t currentTime = now();
3059
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003060 std::vector<EventEntry*> cancelationEvents =
3061 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003063 if (cancelationEvents.empty()) {
3064 return;
3065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003067 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3068 "with reality: %s, mode=%d.",
3069 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3070 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003072
3073 InputTarget target;
3074 sp<InputWindowHandle> windowHandle =
3075 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3076 if (windowHandle != nullptr) {
3077 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003078 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003079 target.globalScaleFactor = windowInfo->globalScaleFactor;
3080 }
3081 target.inputChannel = connection->inputChannel;
3082 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3083
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003084 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3085 EventEntry* cancelationEventEntry = cancelationEvents[i];
3086 switch (cancelationEventEntry->type) {
3087 case EventEntry::Type::KEY: {
3088 logOutboundKeyDetails("cancel - ",
3089 static_cast<const KeyEntry&>(*cancelationEventEntry));
3090 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003092 case EventEntry::Type::MOTION: {
3093 logOutboundMotionDetails("cancel - ",
3094 static_cast<const MotionEntry&>(*cancelationEventEntry));
3095 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003097 case EventEntry::Type::FOCUS: {
3098 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3099 break;
3100 }
3101 case EventEntry::Type::CONFIGURATION_CHANGED:
3102 case EventEntry::Type::DEVICE_RESET: {
3103 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3104 EventEntry::typeToString(cancelationEventEntry->type));
3105 break;
3106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
3108
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003109 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3110 target, InputTarget::FLAG_DISPATCH_AS_IS);
3111
3112 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003114
3115 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116}
3117
Svet Ganov5d3bc372020-01-26 23:11:07 -08003118void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3119 const sp<Connection>& connection) {
3120 if (connection->status == Connection::STATUS_BROKEN) {
3121 return;
3122 }
3123
3124 nsecs_t currentTime = now();
3125
3126 std::vector<EventEntry*> downEvents =
3127 connection->inputState.synthesizePointerDownEvents(currentTime);
3128
3129 if (downEvents.empty()) {
3130 return;
3131 }
3132
3133#if DEBUG_OUTBOUND_EVENT_DETAILS
3134 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3135 connection->getInputChannelName().c_str(), downEvents.size());
3136#endif
3137
3138 InputTarget target;
3139 sp<InputWindowHandle> windowHandle =
3140 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3141 if (windowHandle != nullptr) {
3142 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003143 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003144 target.globalScaleFactor = windowInfo->globalScaleFactor;
3145 }
3146 target.inputChannel = connection->inputChannel;
3147 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3148
3149 for (EventEntry* downEventEntry : downEvents) {
3150 switch (downEventEntry->type) {
3151 case EventEntry::Type::MOTION: {
3152 logOutboundMotionDetails("down - ",
3153 static_cast<const MotionEntry&>(*downEventEntry));
3154 break;
3155 }
3156
3157 case EventEntry::Type::KEY:
3158 case EventEntry::Type::FOCUS:
3159 case EventEntry::Type::CONFIGURATION_CHANGED:
3160 case EventEntry::Type::DEVICE_RESET: {
3161 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3162 EventEntry::typeToString(downEventEntry->type));
3163 break;
3164 }
3165 }
3166
3167 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3168 target, InputTarget::FLAG_DISPATCH_AS_IS);
3169
3170 downEventEntry->release();
3171 }
3172
3173 startDispatchCycleLocked(currentTime, connection);
3174}
3175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003177 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 ALOG_ASSERT(pointerIds.value != 0);
3179
3180 uint32_t splitPointerIndexMap[MAX_POINTERS];
3181 PointerProperties splitPointerProperties[MAX_POINTERS];
3182 PointerCoords splitPointerCoords[MAX_POINTERS];
3183
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003184 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 uint32_t splitPointerCount = 0;
3186
3187 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003190 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 uint32_t pointerId = uint32_t(pointerProperties.id);
3192 if (pointerIds.hasBit(pointerId)) {
3193 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3194 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3195 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003196 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 splitPointerCount += 1;
3198 }
3199 }
3200
3201 if (splitPointerCount != pointerIds.count()) {
3202 // This is bad. We are missing some of the pointers that we expected to deliver.
3203 // Most likely this indicates that we received an ACTION_MOVE events that has
3204 // different pointer ids than we expected based on the previous ACTION_DOWN
3205 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3206 // in this way.
3207 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 "we expected there to be %d pointers. This probably means we received "
3209 "a broken sequence of pointer ids from the input device.",
3210 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003211 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 }
3213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3217 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3219 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003220 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 uint32_t pointerId = uint32_t(pointerProperties.id);
3222 if (pointerIds.hasBit(pointerId)) {
3223 if (pointerIds.count() == 1) {
3224 // The first/last pointer went down/up.
3225 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 ? AMOTION_EVENT_ACTION_DOWN
3227 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 } else {
3229 // A secondary pointer went down/up.
3230 uint32_t splitPointerIndex = 0;
3231 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3232 splitPointerIndex += 1;
3233 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 action = maskedAction |
3235 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237 } else {
3238 // An unrelated pointer changed.
3239 action = AMOTION_EVENT_ACTION_MOVE;
3240 }
3241 }
3242
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003243 int32_t newId = mIdGenerator.nextId();
3244 if (ATRACE_ENABLED()) {
3245 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3246 ") to MotionEvent(id=0x%" PRIx32 ").",
3247 originalMotionEntry.id, newId);
3248 ATRACE_NAME(message.c_str());
3249 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003250 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003251 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3252 originalMotionEntry.source, originalMotionEntry.displayId,
3253 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003254 originalMotionEntry.actionButton, originalMotionEntry.flags,
3255 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3256 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3257 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3258 originalMotionEntry.xCursorPosition,
3259 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003260 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003262 if (originalMotionEntry.injectionState) {
3263 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 splitMotionEntry->injectionState->refCount += 1;
3265 }
3266
3267 return splitMotionEntry;
3268}
3269
3270void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3271#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003272 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273#endif
3274
3275 bool needWake;
3276 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003277 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278
Prabir Pradhan42611e02018-11-27 14:04:02 -08003279 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003280 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 needWake = enqueueInboundEventLocked(newEntry);
3282 } // release lock
3283
3284 if (needWake) {
3285 mLooper->wake();
3286 }
3287}
3288
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003289/**
3290 * If one of the meta shortcuts is detected, process them here:
3291 * Meta + Backspace -> generate BACK
3292 * Meta + Enter -> generate HOME
3293 * This will potentially overwrite keyCode and metaState.
3294 */
3295void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003297 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3298 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3299 if (keyCode == AKEYCODE_DEL) {
3300 newKeyCode = AKEYCODE_BACK;
3301 } else if (keyCode == AKEYCODE_ENTER) {
3302 newKeyCode = AKEYCODE_HOME;
3303 }
3304 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003305 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003306 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003307 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003308 keyCode = newKeyCode;
3309 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3310 }
3311 } else if (action == AKEY_EVENT_ACTION_UP) {
3312 // In order to maintain a consistent stream of up and down events, check to see if the key
3313 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3314 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003315 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003316 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003317 auto replacementIt = mReplacedKeys.find(replacement);
3318 if (replacementIt != mReplacedKeys.end()) {
3319 keyCode = replacementIt->second;
3320 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003321 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3322 }
3323 }
3324}
3325
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3327#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3329 "policyFlags=0x%x, action=0x%x, "
3330 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3331 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3332 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3333 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334#endif
3335 if (!validateKeyEvent(args->action)) {
3336 return;
3337 }
3338
3339 uint32_t policyFlags = args->policyFlags;
3340 int32_t flags = args->flags;
3341 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003342 // InputDispatcher tracks and generates key repeats on behalf of
3343 // whatever notifies it, so repeatCount should always be set to 0
3344 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3346 policyFlags |= POLICY_FLAG_VIRTUAL;
3347 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 if (policyFlags & POLICY_FLAG_FUNCTION) {
3350 metaState |= AMETA_FUNCTION_ON;
3351 }
3352
3353 policyFlags |= POLICY_FLAG_TRUSTED;
3354
Michael Wright78f24442014-08-06 15:55:28 -07003355 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003356 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003357
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003359 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003360 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3361 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Michael Wright2b3c3302018-03-02 17:19:13 +00003363 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003365 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3366 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 bool needWake;
3371 { // acquire lock
3372 mLock.lock();
3373
3374 if (shouldSendKeyToInputFilterLocked(args)) {
3375 mLock.unlock();
3376
3377 policyFlags |= POLICY_FLAG_FILTERED;
3378 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3379 return; // event was consumed by the filter
3380 }
3381
3382 mLock.lock();
3383 }
3384
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003386 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 args->displayId, policyFlags, args->action, flags, keyCode,
3388 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389
3390 needWake = enqueueInboundEventLocked(newEntry);
3391 mLock.unlock();
3392 } // release lock
3393
3394 if (needWake) {
3395 mLooper->wake();
3396 }
3397}
3398
3399bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3400 return mInputFilterEnabled;
3401}
3402
3403void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3404#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003405 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3406 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003407 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3408 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003409 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003410 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3411 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3412 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3413 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 for (uint32_t i = 0; i < args->pointerCount; i++) {
3415 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003416 "x=%f, y=%f, pressure=%f, size=%f, "
3417 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3418 "orientation=%f",
3419 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3420 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3421 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3422 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3423 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3424 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3425 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3426 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3427 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3428 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 }
3430#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3432 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 return;
3434 }
3435
3436 uint32_t policyFlags = args->policyFlags;
3437 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003438
3439 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003440 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003441 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3442 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003443 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445
3446 bool needWake;
3447 { // acquire lock
3448 mLock.lock();
3449
3450 if (shouldSendMotionToInputFilterLocked(args)) {
3451 mLock.unlock();
3452
3453 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003454 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003455 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3456 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003457 args->metaState, args->buttonState, args->classification, transform,
3458 args->xPrecision, args->yPrecision, args->xCursorPosition,
3459 args->yCursorPosition, args->downTime, args->eventTime,
3460 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
3462 policyFlags |= POLICY_FLAG_FILTERED;
3463 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3464 return; // event was consumed by the filter
3465 }
3466
3467 mLock.lock();
3468 }
3469
3470 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003471 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003472 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003473 args->displayId, policyFlags, args->action, args->actionButton,
3474 args->flags, args->metaState, args->buttonState,
3475 args->classification, args->edgeFlags, args->xPrecision,
3476 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3477 args->downTime, args->pointerCount, args->pointerProperties,
3478 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
3480 needWake = enqueueInboundEventLocked(newEntry);
3481 mLock.unlock();
3482 } // release lock
3483
3484 if (needWake) {
3485 mLooper->wake();
3486 }
3487}
3488
3489bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003490 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491}
3492
3493void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3494#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003495 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003496 "switchMask=0x%08x",
3497 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498#endif
3499
3500 uint32_t policyFlags = args->policyFlags;
3501 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003502 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503}
3504
3505void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3506#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3508 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509#endif
3510
3511 bool needWake;
3512 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Prabir Pradhan42611e02018-11-27 14:04:02 -08003515 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003516 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 needWake = enqueueInboundEventLocked(newEntry);
3518 } // release lock
3519
3520 if (needWake) {
3521 mLooper->wake();
3522 }
3523}
3524
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003525InputEventInjectionResult InputDispatcher::injectInputEvent(
3526 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3527 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528#if DEBUG_INBOUND_EVENT_DETAILS
3529 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003530 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3531 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003533 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
3535 policyFlags |= POLICY_FLAG_INJECTED;
3536 if (hasInjectionPermission(injectorPid, injectorUid)) {
3537 policyFlags |= POLICY_FLAG_TRUSTED;
3538 }
3539
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003540 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003542 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003543 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3544 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003545 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003546 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003549 int32_t flags = incomingKey.getFlags();
3550 int32_t keyCode = incomingKey.getKeyCode();
3551 int32_t metaState = incomingKey.getMetaState();
3552 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003553 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003554 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003555 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003556 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3557 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3558 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3561 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003562 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563
3564 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3565 android::base::Timer t;
3566 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3567 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3568 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3569 std::to_string(t.duration().count()).c_str());
3570 }
3571 }
3572
3573 mLock.lock();
3574 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003575 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3576 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003577 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3578 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003579 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 injectedEntries.push(injectedEntry);
3581 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003584 case AINPUT_EVENT_TYPE_MOTION: {
3585 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3586 int32_t action = motionEvent->getAction();
3587 size_t pointerCount = motionEvent->getPointerCount();
3588 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3589 int32_t actionButton = motionEvent->getActionButton();
3590 int32_t displayId = motionEvent->getDisplayId();
3591 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003592 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003593 }
3594
3595 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3596 nsecs_t eventTime = motionEvent->getEventTime();
3597 android::base::Timer t;
3598 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3599 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3600 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3601 std::to_string(t.duration().count()).c_str());
3602 }
3603 }
3604
3605 mLock.lock();
3606 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3607 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3608 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003609 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3610 motionEvent->getSource(), motionEvent->getDisplayId(),
3611 policyFlags, action, actionButton, motionEvent->getFlags(),
3612 motionEvent->getMetaState(), motionEvent->getButtonState(),
3613 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3614 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003615 motionEvent->getRawXCursorPosition(),
3616 motionEvent->getRawYCursorPosition(),
3617 motionEvent->getDownTime(), uint32_t(pointerCount),
3618 pointerProperties, samplePointerCoords,
3619 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620 injectedEntries.push(injectedEntry);
3621 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3622 sampleEventTimes += 1;
3623 samplePointerCoords += pointerCount;
3624 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003625 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003626 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 motionEvent->getDisplayId(), policyFlags, action,
3628 actionButton, motionEvent->getFlags(),
3629 motionEvent->getMetaState(), motionEvent->getButtonState(),
3630 motionEvent->getClassification(),
3631 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3632 motionEvent->getYPrecision(),
3633 motionEvent->getRawXCursorPosition(),
3634 motionEvent->getRawYCursorPosition(),
3635 motionEvent->getDownTime(), uint32_t(pointerCount),
3636 pointerProperties, samplePointerCoords,
3637 motionEvent->getXOffset(), motionEvent->getYOffset());
3638 injectedEntries.push(nextInjectedEntry);
3639 }
3640 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003643 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003644 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003645 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647
3648 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003649 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 injectionState->injectionIsAsync = true;
3651 }
3652
3653 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003654 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655
3656 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003657 while (!injectedEntries.empty()) {
3658 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3659 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
3662 mLock.unlock();
3663
3664 if (needWake) {
3665 mLooper->wake();
3666 }
3667
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003668 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003670 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003672 if (syncMode == InputEventInjectionSync::NONE) {
3673 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 } else {
3675 for (;;) {
3676 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003677 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 break;
3679 }
3680
3681 nsecs_t remainingTimeout = endTime - now();
3682 if (remainingTimeout <= 0) {
3683#if DEBUG_INJECTION
3684 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003685 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003687 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 break;
3689 }
3690
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003691 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 }
3693
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003694 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3695 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 while (injectionState->pendingForegroundDispatches != 0) {
3697#if DEBUG_INJECTION
3698 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003699 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700#endif
3701 nsecs_t remainingTimeout = endTime - now();
3702 if (remainingTimeout <= 0) {
3703#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003704 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3705 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003707 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 break;
3709 }
3710
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003711 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713 }
3714 }
3715
3716 injectionState->release();
3717 } // release lock
3718
3719#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003720 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722#endif
3723
3724 return injectionResult;
3725}
3726
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003727std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003728 std::array<uint8_t, 32> calculatedHmac;
3729 std::unique_ptr<VerifiedInputEvent> result;
3730 switch (event.getType()) {
3731 case AINPUT_EVENT_TYPE_KEY: {
3732 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3733 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3734 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003735 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003736 break;
3737 }
3738 case AINPUT_EVENT_TYPE_MOTION: {
3739 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3740 VerifiedMotionEvent verifiedMotionEvent =
3741 verifiedMotionEventFromMotionEvent(motionEvent);
3742 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003743 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003744 break;
3745 }
3746 default: {
3747 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3748 return nullptr;
3749 }
3750 }
3751 if (calculatedHmac == INVALID_HMAC) {
3752 return nullptr;
3753 }
3754 if (calculatedHmac != event.getHmac()) {
3755 return nullptr;
3756 }
3757 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003758}
3759
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 return injectorUid == 0 ||
3762 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763}
3764
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003765void InputDispatcher::setInjectionResult(EventEntry* entry,
3766 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 InjectionState* injectionState = entry->injectionState;
3768 if (injectionState) {
3769#if DEBUG_INJECTION
3770 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 "injectorPid=%d, injectorUid=%d",
3772 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773#endif
3774
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003775 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 // Log the outcome since the injector did not wait for the injection result.
3777 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003778 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 ALOGV("Asynchronous input event injection succeeded.");
3780 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003781 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 ALOGW("Asynchronous input event injection failed.");
3783 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003784 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 ALOGW("Asynchronous input event injection permission denied.");
3786 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003787 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 ALOGW("Asynchronous input event injection timed out.");
3789 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003790 case InputEventInjectionResult::PENDING:
3791 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3792 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794 }
3795
3796 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003797 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 }
3799}
3800
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003801void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 InjectionState* injectionState = entry->injectionState;
3803 if (injectionState) {
3804 injectionState->pendingForegroundDispatches += 1;
3805 }
3806}
3807
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003808void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 InjectionState* injectionState = entry->injectionState;
3810 if (injectionState) {
3811 injectionState->pendingForegroundDispatches -= 1;
3812
3813 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003814 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 }
3817}
3818
Vishnu Nairad321cd2020-08-20 16:40:21 -07003819const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003820 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003821 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3822 auto it = mWindowHandlesByDisplay.find(displayId);
3823 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003824}
3825
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003827 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003828 if (windowHandleToken == nullptr) {
3829 return nullptr;
3830 }
3831
Arthur Hungb92218b2018-08-14 12:00:21 +08003832 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003833 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003834 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003835 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003836 return windowHandle;
3837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003840 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841}
3842
Vishnu Nairad321cd2020-08-20 16:40:21 -07003843sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3844 int displayId) const {
3845 if (windowHandleToken == nullptr) {
3846 return nullptr;
3847 }
3848
3849 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3850 if (windowHandle->getToken() == windowHandleToken) {
3851 return windowHandle;
3852 }
3853 }
3854 return nullptr;
3855}
3856
3857sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3858 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3859 return getWindowHandleLocked(focusedToken, displayId);
3860}
3861
Mady Mellor017bcd12020-06-23 19:12:00 +00003862bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3863 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003864 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003865 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003866 if (handle->getId() == windowHandle->getId() &&
3867 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003868 if (windowHandle->getInfo()->displayId != it.first) {
3869 ALOGE("Found window %s in display %" PRId32
3870 ", but it should belong to display %" PRId32,
3871 windowHandle->getName().c_str(), it.first,
3872 windowHandle->getInfo()->displayId);
3873 }
3874 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877 }
3878 return false;
3879}
3880
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003881bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3882 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3883 const bool noInputChannel =
3884 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3885 if (connection != nullptr && noInputChannel) {
3886 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3887 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3888 return false;
3889 }
3890
3891 if (connection == nullptr) {
3892 if (!noInputChannel) {
3893 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3894 }
3895 return false;
3896 }
3897 if (!connection->responsive) {
3898 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3899 return false;
3900 }
3901 return true;
3902}
3903
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003904std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3905 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003906 size_t count = mInputChannelsByToken.count(token);
3907 if (count == 0) {
3908 return nullptr;
3909 }
3910 return mInputChannelsByToken.at(token);
3911}
3912
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003913void InputDispatcher::updateWindowHandlesForDisplayLocked(
3914 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3915 if (inputWindowHandles.empty()) {
3916 // Remove all handles on a display if there are no windows left.
3917 mWindowHandlesByDisplay.erase(displayId);
3918 return;
3919 }
3920
3921 // Since we compare the pointer of input window handles across window updates, we need
3922 // to make sure the handle object for the same window stays unchanged across updates.
3923 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003924 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003925 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003926 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003927 }
3928
3929 std::vector<sp<InputWindowHandle>> newHandles;
3930 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3931 if (!handle->updateInfo()) {
3932 // handle no longer valid
3933 continue;
3934 }
3935
3936 const InputWindowInfo* info = handle->getInfo();
3937 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3938 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3939 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003940 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3941 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3942 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003943 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003944 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003945 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003946 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003947 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003948 }
3949
3950 if (info->displayId != displayId) {
3951 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3952 handle->getName().c_str(), displayId, info->displayId);
3953 continue;
3954 }
3955
Robert Carredd13602020-04-13 17:24:34 -07003956 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3957 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003958 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003959 oldHandle->updateFrom(handle);
3960 newHandles.push_back(oldHandle);
3961 } else {
3962 newHandles.push_back(handle);
3963 }
3964 }
3965
3966 // Insert or replace
3967 mWindowHandlesByDisplay[displayId] = newHandles;
3968}
3969
Arthur Hung72d8dc32020-03-28 00:48:39 +00003970void InputDispatcher::setInputWindows(
3971 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3972 { // acquire lock
3973 std::scoped_lock _l(mLock);
3974 for (auto const& i : handlesPerDisplay) {
3975 setInputWindowsLocked(i.second, i.first);
3976 }
3977 }
3978 // Wake up poll loop since it may need to make new input dispatching choices.
3979 mLooper->wake();
3980}
3981
Arthur Hungb92218b2018-08-14 12:00:21 +08003982/**
3983 * Called from InputManagerService, update window handle list by displayId that can receive input.
3984 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3985 * If set an empty list, remove all handles from the specific display.
3986 * For focused handle, check if need to change and send a cancel event to previous one.
3987 * For removed handle, check if need to send a cancel event if already in touch.
3988 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003989void InputDispatcher::setInputWindowsLocked(
3990 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003991 if (DEBUG_FOCUS) {
3992 std::string windowList;
3993 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3994 windowList += iwh->getName() + " ";
3995 }
3996 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003999 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4000 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4001 const bool noInputWindow =
4002 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4003 if (noInputWindow && window->getToken() != nullptr) {
4004 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4005 window->getName().c_str());
4006 window->releaseChannel();
4007 }
4008 }
4009
Arthur Hung72d8dc32020-03-28 00:48:39 +00004010 // Copy old handles for release if they are no longer present.
4011 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Arthur Hung72d8dc32020-03-28 00:48:39 +00004013 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004014
Vishnu Nair958da932020-08-21 17:12:37 -07004015 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4016 if (mLastHoverWindowHandle &&
4017 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4018 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004019 mLastHoverWindowHandle = nullptr;
4020 }
4021
Vishnu Nair958da932020-08-21 17:12:37 -07004022 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4023 if (focusedToken) {
4024 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4025 if (result != FocusResult::OK) {
4026 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4027 }
4028 }
4029
4030 std::optional<FocusRequest> focusRequest =
4031 getOptionalValueByKey(mPendingFocusRequests, displayId);
4032 if (focusRequest) {
4033 // If the window from the pending request is now visible, provide it focus.
4034 FocusResult result = handleFocusRequestLocked(*focusRequest);
4035 if (result != FocusResult::NOT_VISIBLE) {
4036 // Drop the request if we were able to change the focus or we cannot change
4037 // it for another reason.
4038 mPendingFocusRequests.erase(displayId);
4039 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004042 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4043 mTouchStatesByDisplay.find(displayId);
4044 if (stateIt != mTouchStatesByDisplay.end()) {
4045 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004046 for (size_t i = 0; i < state.windows.size();) {
4047 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004048 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004049 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004050 ALOGD("Touched window was removed: %s in display %" PRId32,
4051 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004052 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004053 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004054 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4055 if (touchedInputChannel != nullptr) {
4056 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4057 "touched window was removed");
4058 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004060 state.windows.erase(state.windows.begin() + i);
4061 } else {
4062 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 }
4064 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004065 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004066
Arthur Hung72d8dc32020-03-28 00:48:39 +00004067 // Release information for windows that are no longer present.
4068 // This ensures that unused input channels are released promptly.
4069 // Otherwise, they might stick around until the window handle is destroyed
4070 // which might not happen until the next GC.
4071 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004072 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004073 if (DEBUG_FOCUS) {
4074 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004075 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004076 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004077 }
chaviw291d88a2019-02-14 10:33:58 -08004078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079}
4080
4081void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004082 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004083 if (DEBUG_FOCUS) {
4084 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4085 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4086 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004087 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004088 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Chris Yea209fde2020-07-22 13:54:51 -07004090 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004091 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004092
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004093 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4094 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004095 }
4096
Chris Yea209fde2020-07-22 13:54:51 -07004097 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004098 if (inputApplicationHandle != nullptr) {
4099 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4100 } else {
4101 mFocusedApplicationHandlesByDisplay.erase(displayId);
4102 }
4103
4104 // No matter what the old focused application was, stop waiting on it because it is
4105 // no longer focused.
4106 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 } // release lock
4108
4109 // Wake up poll loop since it may need to make new input dispatching choices.
4110 mLooper->wake();
4111}
4112
Tiger Huang721e26f2018-07-24 22:26:19 +08004113/**
4114 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4115 * the display not specified.
4116 *
4117 * We track any unreleased events for each window. If a window loses the ability to receive the
4118 * released event, we will send a cancel event to it. So when the focused display is changed, we
4119 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4120 * display. The display-specified events won't be affected.
4121 */
4122void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004123 if (DEBUG_FOCUS) {
4124 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4125 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004126 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004127 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004128
4129 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004130 sp<IBinder> oldFocusedWindowToken =
4131 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4132 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004133 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004134 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004135 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 CancelationOptions
4137 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4138 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004139 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004140 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4141 }
4142 }
4143 mFocusedDisplayId = displayId;
4144
Chris Ye3c2d6f52020-08-09 10:39:48 -07004145 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004146 sp<IBinder> newFocusedWindowToken =
4147 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4148 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004149
Vishnu Nairad321cd2020-08-20 16:40:21 -07004150 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004151 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004152 if (!mFocusedWindowTokenByDisplay.empty()) {
4153 ALOGE("But another display has a focused window\n%s",
4154 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004155 }
4156 }
4157 }
4158
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004159 if (DEBUG_FOCUS) {
4160 logDispatchStateLocked();
4161 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004162 } // release lock
4163
4164 // Wake up poll loop since it may need to make new input dispatching choices.
4165 mLooper->wake();
4166}
4167
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004169 if (DEBUG_FOCUS) {
4170 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
4173 bool changed;
4174 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
4177 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4178 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004179 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181
4182 if (mDispatchEnabled && !enabled) {
4183 resetAndDropEverythingLocked("dispatcher is being disabled");
4184 }
4185
4186 mDispatchEnabled = enabled;
4187 mDispatchFrozen = frozen;
4188 changed = true;
4189 } else {
4190 changed = false;
4191 }
4192
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004193 if (DEBUG_FOCUS) {
4194 logDispatchStateLocked();
4195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 } // release lock
4197
4198 if (changed) {
4199 // Wake up poll loop since it may need to make new input dispatching choices.
4200 mLooper->wake();
4201 }
4202}
4203
4204void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004205 if (DEBUG_FOCUS) {
4206 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
4209 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004210 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
4212 if (mInputFilterEnabled == enabled) {
4213 return;
4214 }
4215
4216 mInputFilterEnabled = enabled;
4217 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4218 } // release lock
4219
4220 // Wake up poll loop since there might be work to do to drop everything.
4221 mLooper->wake();
4222}
4223
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004224void InputDispatcher::setInTouchMode(bool inTouchMode) {
4225 std::scoped_lock lock(mLock);
4226 mInTouchMode = inTouchMode;
4227}
4228
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004229void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4230 if (opacity < 0 || opacity > 1) {
4231 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4232 return;
4233 }
4234
4235 std::scoped_lock lock(mLock);
4236 mMaximumObscuringOpacityForTouch = opacity;
4237}
4238
4239void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4240 std::scoped_lock lock(mLock);
4241 mBlockUntrustedTouchesMode = mode;
4242}
4243
chaviwfbe5d9c2018-12-26 12:23:37 -08004244bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4245 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004246 if (DEBUG_FOCUS) {
4247 ALOGD("Trivial transfer to same window.");
4248 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004249 return true;
4250 }
4251
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004253 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254
chaviwfbe5d9c2018-12-26 12:23:37 -08004255 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4256 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004257 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004258 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 return false;
4260 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004261 if (DEBUG_FOCUS) {
4262 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4263 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004266 if (DEBUG_FOCUS) {
4267 ALOGD("Cannot transfer focus because windows are on different displays.");
4268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 return false;
4270 }
4271
4272 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004273 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4274 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004275 for (size_t i = 0; i < state.windows.size(); i++) {
4276 const TouchedWindow& touchedWindow = state.windows[i];
4277 if (touchedWindow.windowHandle == fromWindowHandle) {
4278 int32_t oldTargetFlags = touchedWindow.targetFlags;
4279 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004281 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 int32_t newTargetFlags = oldTargetFlags &
4284 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4285 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004286 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287
Jeff Brownf086ddb2014-02-11 14:28:48 -08004288 found = true;
4289 goto Found;
4290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004296 if (DEBUG_FOCUS) {
4297 ALOGD("Focus transfer failed because from window did not have focus.");
4298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 return false;
4300 }
4301
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004302 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4303 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004304 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004305 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 CancelationOptions
4307 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4308 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004310 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004313 if (DEBUG_FOCUS) {
4314 logDispatchStateLocked();
4315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 } // release lock
4317
4318 // Wake up poll loop since it may need to make new input dispatching choices.
4319 mLooper->wake();
4320 return true;
4321}
4322
4323void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004324 if (DEBUG_FOCUS) {
4325 ALOGD("Resetting and dropping all events (%s).", reason);
4326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
4328 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4329 synthesizeCancelationEventsForAllConnectionsLocked(options);
4330
4331 resetKeyRepeatLocked();
4332 releasePendingEventLocked();
4333 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004334 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004336 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004337 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004339 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340}
4341
4342void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004343 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 dumpDispatchStateLocked(dump);
4345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346 std::istringstream stream(dump);
4347 std::string line;
4348
4349 while (std::getline(stream, line, '\n')) {
4350 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
4352}
4353
Vishnu Nairad321cd2020-08-20 16:40:21 -07004354std::string InputDispatcher::dumpFocusedWindowsLocked() {
4355 if (mFocusedWindowTokenByDisplay.empty()) {
4356 return INDENT "FocusedWindows: <none>\n";
4357 }
4358
4359 std::string dump;
4360 dump += INDENT "FocusedWindows:\n";
4361 for (auto& it : mFocusedWindowTokenByDisplay) {
4362 const int32_t displayId = it.first;
4363 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4364 if (windowHandle) {
4365 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4366 windowHandle->getName().c_str());
4367 } else {
4368 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4369 " has focused token without a window'\n",
4370 displayId);
4371 }
4372 }
4373 return dump;
4374}
4375
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004376void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004377 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4378 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4379 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004380 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Tiger Huang721e26f2018-07-24 22:26:19 +08004382 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4383 dump += StringPrintf(INDENT "FocusedApplications:\n");
4384 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4385 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004386 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004387 const std::chrono::duration timeout =
4388 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004390 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004391 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004394 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004396
Vishnu Nairad321cd2020-08-20 16:40:21 -07004397 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004399 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004400 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004401 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4402 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004403 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 state.displayId, toString(state.down), toString(state.split),
4405 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004406 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004407 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004408 for (size_t i = 0; i < state.windows.size(); i++) {
4409 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 dump += StringPrintf(INDENT4
4411 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4412 i, touchedWindow.windowHandle->getName().c_str(),
4413 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004414 }
4415 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004416 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004417 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004418 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004419 dump += INDENT3 "Portal windows:\n";
4420 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004421 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4423 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004424 }
4425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 }
4427 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004428 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 }
4430
Arthur Hungb92218b2018-08-14 12:00:21 +08004431 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004432 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004433 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004434 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004435 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004436 dump += INDENT2 "Windows:\n";
4437 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004438 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004439 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440
Arthur Hungb92218b2018-08-14 12:00:21 +08004441 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004442 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4443 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004444 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004446 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004447 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 i, windowInfo->name.c_str(), windowInfo->displayId,
4449 windowInfo->portalToDisplayId,
4450 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004451 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 toString(windowInfo->hasWallpaper),
4453 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004454 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004455 static_cast<int32_t>(windowInfo->type),
4456 windowInfo->frameLeft, windowInfo->frameTop,
4457 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004458 windowInfo->globalScaleFactor,
4459 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004460 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004461 dump += StringPrintf(", inputFeatures=%s",
4462 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004463 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4464 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004465 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004466 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004467 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004468 }
4469 } else {
4470 dump += INDENT2 "Windows: <none>\n";
4471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 }
4473 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004474 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
4476
Michael Wright3dd60e22019-03-27 22:06:44 +00004477 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004479 const std::vector<Monitor>& monitors = it.second;
4480 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4481 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 }
4483 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004484 const std::vector<Monitor>& monitors = it.second;
4485 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4486 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004489 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 }
4491
4492 nsecs_t currentTime = now();
4493
4494 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004495 if (!mRecentQueue.empty()) {
4496 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4497 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004498 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004499 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004500 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
4502 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004503 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
4505
4506 // Dump event currently being dispatched.
4507 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004508 dump += INDENT "PendingEvent:\n";
4509 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004510 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004511 dump += StringPrintf(", age=%" PRId64 "ms\n",
4512 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004514 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516
4517 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004518 if (!mInboundQueue.empty()) {
4519 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4520 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004521 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004522 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004523 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 }
4525 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004526 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 }
4528
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004529 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004530 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004531 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4532 const KeyReplacement& replacement = pair.first;
4533 int32_t newKeyCode = pair.second;
4534 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004535 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004536 }
4537 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004538 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004539 }
4540
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004541 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004542 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004543 for (const auto& pair : mConnectionsByFd) {
4544 const sp<Connection>& connection = pair.second;
4545 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004547 pair.first, connection->getInputChannelName().c_str(),
4548 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004551 if (!connection->outboundQueue.empty()) {
4552 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4553 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004554 dump += dumpQueue(connection->outboundQueue, currentTime);
4555
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004557 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004560 if (!connection->waitQueue.empty()) {
4561 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4562 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004563 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004565 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 }
4567 }
4568 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004569 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 }
4571
4572 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004573 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4574 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004576 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 }
4578
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004579 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004580 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4581 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4582 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583}
4584
Michael Wright3dd60e22019-03-27 22:06:44 +00004585void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4586 const size_t numMonitors = monitors.size();
4587 for (size_t i = 0; i < numMonitors; i++) {
4588 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004589 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004590 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4591 dump += "\n";
4592 }
4593}
4594
Garfield Tan15601662020-09-22 15:32:38 -07004595base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4596 const std::string& name) {
4597#if DEBUG_CHANNEL_CREATION
4598 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599#endif
4600
Garfield Tan15601662020-09-22 15:32:38 -07004601 std::shared_ptr<InputChannel> serverChannel;
4602 std::unique_ptr<InputChannel> clientChannel;
4603 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4604
4605 if (result) {
4606 return base::Error(result) << "Failed to open input channel pair with name " << name;
4607 }
4608
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004610 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004611 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
Garfield Tan15601662020-09-22 15:32:38 -07004613 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004614 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004615 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4618 } // release lock
4619
4620 // Wake the looper because some connections have changed.
4621 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004622 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623}
4624
Garfield Tan15601662020-09-22 15:32:38 -07004625base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4626 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4627 std::shared_ptr<InputChannel> serverChannel;
4628 std::unique_ptr<InputChannel> clientChannel;
4629 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4630 if (result) {
4631 return base::Error(result) << "Failed to open input channel pair with name " << name;
4632 }
4633
Michael Wright3dd60e22019-03-27 22:06:44 +00004634 { // acquire lock
4635 std::scoped_lock _l(mLock);
4636
4637 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004638 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4639 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004640 }
4641
Garfield Tan15601662020-09-22 15:32:38 -07004642 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004643
Garfield Tan15601662020-09-22 15:32:38 -07004644 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004645 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004646 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648 auto& monitorsByDisplay =
4649 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004650 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004651
4652 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004653 }
Garfield Tan15601662020-09-22 15:32:38 -07004654
Michael Wright3dd60e22019-03-27 22:06:44 +00004655 // Wake the looper because some connections have changed.
4656 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004657 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004658}
4659
Garfield Tan15601662020-09-22 15:32:38 -07004660status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004662 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663
Garfield Tan15601662020-09-22 15:32:38 -07004664 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 if (status) {
4666 return status;
4667 }
4668 } // release lock
4669
4670 // Wake the poll loop because removing the connection may have changed the current
4671 // synchronization state.
4672 mLooper->wake();
4673 return OK;
4674}
4675
Garfield Tan15601662020-09-22 15:32:38 -07004676status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4677 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004678 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004679 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004680 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 return BAD_VALUE;
4682 }
4683
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004684 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004685 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004686
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004688 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 }
4690
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004691 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
4693 nsecs_t currentTime = now();
4694 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4695
4696 connection->status = Connection::STATUS_ZOMBIE;
4697 return OK;
4698}
4699
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004700void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4701 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4702 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004703}
4704
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004705void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004706 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004707 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004709 std::vector<Monitor>& monitors = it->second;
4710 const size_t numMonitors = monitors.size();
4711 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004712 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 monitors.erase(monitors.begin() + i);
4714 break;
4715 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004716 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004717 if (monitors.empty()) {
4718 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004719 } else {
4720 ++it;
4721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 }
4723}
4724
Michael Wright3dd60e22019-03-27 22:06:44 +00004725status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4726 { // acquire lock
4727 std::scoped_lock _l(mLock);
4728 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4729
4730 if (!foundDisplayId) {
4731 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4732 return BAD_VALUE;
4733 }
4734 int32_t displayId = foundDisplayId.value();
4735
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004736 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4737 mTouchStatesByDisplay.find(displayId);
4738 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004739 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4740 return BAD_VALUE;
4741 }
4742
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004743 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004744 std::optional<int32_t> foundDeviceId;
4745 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004746 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004747 foundDeviceId = state.deviceId;
4748 }
4749 }
4750 if (!foundDeviceId || !state.down) {
4751 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004753 return BAD_VALUE;
4754 }
4755 int32_t deviceId = foundDeviceId.value();
4756
4757 // Send cancel events to all the input channels we're stealing from.
4758 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004759 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004760 options.deviceId = deviceId;
4761 options.displayId = displayId;
4762 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004763 std::shared_ptr<InputChannel> channel =
4764 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004765 if (channel != nullptr) {
4766 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4767 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004768 }
4769 // Then clear the current touch state so we stop dispatching to them as well.
4770 state.filterNonMonitors();
4771 }
4772 return OK;
4773}
4774
Michael Wright3dd60e22019-03-27 22:06:44 +00004775std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4776 const sp<IBinder>& token) {
4777 for (const auto& it : mGestureMonitorsByDisplay) {
4778 const std::vector<Monitor>& monitors = it.second;
4779 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004780 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004781 return it.first;
4782 }
4783 }
4784 }
4785 return std::nullopt;
4786}
4787
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004788sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004789 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004790 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004791 }
4792
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004793 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004794 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004795 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004796 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798 }
Robert Carr4e670e52018-08-15 13:26:12 -07004799
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004800 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801}
4802
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004803void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004805 removeByValue(mConnectionsByFd, connection);
4806}
4807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4809 const sp<Connection>& connection, uint32_t seq,
4810 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004811 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4812 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 commandEntry->connection = connection;
4814 commandEntry->eventTime = currentTime;
4815 commandEntry->seq = seq;
4816 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004817 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818}
4819
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004820void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4821 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004825 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4826 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004828 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829}
4830
Vishnu Nairad321cd2020-08-20 16:40:21 -07004831void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4832 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004833 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4834 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004835 commandEntry->oldToken = oldToken;
4836 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004837 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004838}
4839
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004840void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4842 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004843 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004845 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 return;
4847 }
4848 /**
4849 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4850 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4851 * has changed. This could cause newer entries to time out before the already dispatched
4852 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4853 * processes the events linearly. So providing information about the oldest entry seems to be
4854 * most useful.
4855 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004856 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4858 std::string reason =
4859 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004860 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 ns2ms(currentWait),
4862 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004864 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865 reason);
4866
4867 std::unique_ptr<CommandEntry> commandEntry =
4868 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4869 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004870 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004871 commandEntry->reason = std::move(reason);
4872 postCommandLocked(std::move(commandEntry));
4873}
4874
Chris Yea209fde2020-07-22 13:54:51 -07004875void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4877 application->getName().c_str());
4878
4879 updateLastAnrStateLocked(application, reason);
4880
4881 std::unique_ptr<CommandEntry> commandEntry =
4882 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4883 commandEntry->inputApplicationHandle = application;
4884 commandEntry->inputChannel = nullptr;
4885 commandEntry->reason = std::move(reason);
4886 postCommandLocked(std::move(commandEntry));
4887}
4888
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004889void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4890 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4891 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4892 commandEntry->obscuringPackage = obscuringPackage;
4893 postCommandLocked(std::move(commandEntry));
4894}
4895
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4897 const std::string& reason) {
4898 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4899 updateLastAnrStateLocked(windowLabel, reason);
4900}
4901
Chris Yea209fde2020-07-22 13:54:51 -07004902void InputDispatcher::updateLastAnrStateLocked(
4903 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4905 updateLastAnrStateLocked(windowLabel, reason);
4906}
4907
4908void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4909 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004911 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 struct tm tm;
4913 localtime_r(&t, &tm);
4914 char timestr[64];
4915 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004916 mLastAnrState.clear();
4917 mLastAnrState += INDENT "ANR:\n";
4918 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4920 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004921 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922}
4923
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004924void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 mLock.unlock();
4926
4927 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4928
4929 mLock.lock();
4930}
4931
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 sp<Connection> connection = commandEntry->connection;
4934
4935 if (connection->status != Connection::STATUS_ZOMBIE) {
4936 mLock.unlock();
4937
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004938 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
4940 mLock.lock();
4941 }
4942}
4943
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004944void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004945 sp<IBinder> oldToken = commandEntry->oldToken;
4946 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004947 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004948 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004949 mLock.lock();
4950}
4951
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004952void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004953 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004954 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 mLock.unlock();
4956
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004957 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004958 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959
4960 mLock.lock();
4961
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004962 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4964 } else {
4965 // stop waking up for events in this connection, it is already not responding
4966 sp<Connection> connection = getConnectionLocked(token);
4967 if (connection == nullptr) {
4968 return;
4969 }
4970 cancelEventsForAnrLocked(connection);
4971 }
4972}
4973
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004974void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
4975 mLock.unlock();
4976
4977 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
4978
4979 mLock.lock();
4980}
4981
Chris Yea209fde2020-07-22 13:54:51 -07004982void InputDispatcher::extendAnrTimeoutsLocked(
4983 const std::shared_ptr<InputApplicationHandle>& application,
4984 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004985 if (connectionToken == nullptr && application != nullptr) {
4986 // The ANR happened because there's no focused window
4987 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4988 mAwaitedFocusedApplication = application;
4989 }
4990
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991 sp<Connection> connection = getConnectionLocked(connectionToken);
4992 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004993 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004994 return;
4995 }
4996
4997 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004998 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999
5000 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005001 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002 for (DispatchEntry* entry : connection->waitQueue) {
5003 if (newTimeout >= entry->timeoutTime) {
5004 // Already removed old entries when connection was marked unresponsive
5005 entry->timeoutTime = newTimeout;
5006 mAnrTracker.insert(entry->timeoutTime, connectionToken);
5007 }
5008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
5011void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5012 CommandEntry* commandEntry) {
5013 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005014 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015
5016 mLock.unlock();
5017
Michael Wright2b3c3302018-03-02 17:19:13 +00005018 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005020 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005021 : nullptr;
5022 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005023 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5024 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005025 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027
5028 mLock.lock();
5029
5030 if (delay < 0) {
5031 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5032 } else if (!delay) {
5033 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5034 } else {
5035 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5036 entry->interceptKeyWakeupTime = now() + delay;
5037 }
5038 entry->release();
5039}
5040
chaviwfd6d3512019-03-25 13:23:49 -07005041void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5042 mLock.unlock();
5043 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5044 mLock.lock();
5045}
5046
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047/**
5048 * Connection is responsive if it has no events in the waitQueue that are older than the
5049 * current time.
5050 */
5051static bool isConnectionResponsive(const Connection& connection) {
5052 const nsecs_t currentTime = now();
5053 for (const DispatchEntry* entry : connection.waitQueue) {
5054 if (entry->timeoutTime < currentTime) {
5055 return false;
5056 }
5057 }
5058 return true;
5059}
5060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005061void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005063 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005065 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066
5067 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005068 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005069 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005070 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005072 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005073 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005074 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005075 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5076 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005077 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005078 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005079
5080 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005081 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005082 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5083 restartEvent =
5084 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005085 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005086 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5087 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5088 handled);
5089 } else {
5090 restartEvent = false;
5091 }
5092
5093 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005094 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005095 // contents of the wait queue to have been drained, so we need to double-check
5096 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005097 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5098 if (dispatchEntryIt != connection->waitQueue.end()) {
5099 dispatchEntry = *dispatchEntryIt;
5100 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005101 mAnrTracker.erase(dispatchEntry->timeoutTime,
5102 connection->inputChannel->getConnectionToken());
5103 if (!connection->responsive) {
5104 connection->responsive = isConnectionResponsive(*connection);
5105 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005106 traceWaitQueueLength(connection);
5107 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005108 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005109 traceOutboundQueueLength(connection);
5110 } else {
5111 releaseDispatchEntry(dispatchEntry);
5112 }
5113 }
5114
5115 // Start the next dispatch cycle for this connection.
5116 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117}
5118
5119bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005120 DispatchEntry* dispatchEntry,
5121 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005122 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005123 if (!handled) {
5124 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005125 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005126 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005127 return false;
5128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005130 // Get the fallback key state.
5131 // Clear it out after dispatching the UP.
5132 int32_t originalKeyCode = keyEntry->keyCode;
5133 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5134 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5135 connection->inputState.removeFallbackKey(originalKeyCode);
5136 }
5137
5138 if (handled || !dispatchEntry->hasForegroundTarget()) {
5139 // If the application handles the original key for which we previously
5140 // generated a fallback or if the window is not a foreground window,
5141 // then cancel the associated fallback key, if any.
5142 if (fallbackKeyCode != -1) {
5143 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005145 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005146 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5147 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5148 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005150 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005151 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152
5153 mLock.unlock();
5154
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005155 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157
5158 mLock.lock();
5159
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005160 // Cancel the fallback key.
5161 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005163 "application handled the original non-fallback key "
5164 "or is no longer a foreground target, "
5165 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 options.keyCode = fallbackKeyCode;
5167 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005169 connection->inputState.removeFallbackKey(originalKeyCode);
5170 }
5171 } else {
5172 // If the application did not handle a non-fallback key, first check
5173 // that we are in a good state to perform unhandled key event processing
5174 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005176 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005178 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005179 "since this is not an initial down. "
5180 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5181 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005183 return false;
5184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005186 // Dispatch the unhandled key to the policy.
5187#if DEBUG_OUTBOUND_EVENT_DETAILS
5188 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005189 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5190 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005191#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005192 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005193
5194 mLock.unlock();
5195
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005196 bool fallback =
5197 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5198 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005199
5200 mLock.lock();
5201
5202 if (connection->status != Connection::STATUS_NORMAL) {
5203 connection->inputState.removeFallbackKey(originalKeyCode);
5204 return false;
5205 }
5206
5207 // Latch the fallback keycode for this key on an initial down.
5208 // The fallback keycode cannot change at any other point in the lifecycle.
5209 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005211 fallbackKeyCode = event.getKeyCode();
5212 } else {
5213 fallbackKeyCode = AKEYCODE_UNKNOWN;
5214 }
5215 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5216 }
5217
5218 ALOG_ASSERT(fallbackKeyCode != -1);
5219
5220 // Cancel the fallback key if the policy decides not to send it anymore.
5221 // We will continue to dispatch the key to the policy but we will no
5222 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005223 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5224 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005225#if DEBUG_OUTBOUND_EVENT_DETAILS
5226 if (fallback) {
5227 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005228 "as a fallback for %d, but on the DOWN it had requested "
5229 "to send %d instead. Fallback canceled.",
5230 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005231 } else {
5232 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005233 "but on the DOWN it had requested to send %d. "
5234 "Fallback canceled.",
5235 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005236 }
5237#endif
5238
5239 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5240 "canceling fallback, policy no longer desires it");
5241 options.keyCode = fallbackKeyCode;
5242 synthesizeCancelationEventsForConnectionLocked(connection, options);
5243
5244 fallback = false;
5245 fallbackKeyCode = AKEYCODE_UNKNOWN;
5246 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005247 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005248 }
5249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
5251#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005252 {
5253 std::string msg;
5254 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5255 connection->inputState.getFallbackKeys();
5256 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005259 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005260 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005261 }
5262#endif
5263
5264 if (fallback) {
5265 // Restart the dispatch cycle using the fallback key.
5266 keyEntry->eventTime = event.getEventTime();
5267 keyEntry->deviceId = event.getDeviceId();
5268 keyEntry->source = event.getSource();
5269 keyEntry->displayId = event.getDisplayId();
5270 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5271 keyEntry->keyCode = fallbackKeyCode;
5272 keyEntry->scanCode = event.getScanCode();
5273 keyEntry->metaState = event.getMetaState();
5274 keyEntry->repeatCount = event.getRepeatCount();
5275 keyEntry->downTime = event.getDownTime();
5276 keyEntry->syntheticRepeat = false;
5277
5278#if DEBUG_OUTBOUND_EVENT_DETAILS
5279 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5281 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005282#endif
5283 return true; // restart the event
5284 } else {
5285#if DEBUG_OUTBOUND_EVENT_DETAILS
5286 ALOGD("Unhandled key event: No fallback key.");
5287#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005288
5289 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005290 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 }
5292 }
5293 return false;
5294}
5295
5296bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005297 DispatchEntry* dispatchEntry,
5298 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 return false;
5300}
5301
5302void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5303 mLock.unlock();
5304
5305 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5306
5307 mLock.lock();
5308}
5309
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005310KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5311 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005312 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005313 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5314 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005315 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316}
5317
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005318void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5319 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 // TODO Write some statistics about how long we spend waiting.
5321}
5322
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005323/**
5324 * Report the touch event latency to the statsd server.
5325 * Input events are reported for statistics if:
5326 * - This is a touchscreen event
5327 * - InputFilter is not enabled
5328 * - Event is not injected or synthesized
5329 *
5330 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5331 * from getting aggregated with the "old" data.
5332 */
5333void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5334 REQUIRES(mLock) {
5335 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5336 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5337 if (!reportForStatistics) {
5338 return;
5339 }
5340
5341 if (mTouchStatistics.shouldReport()) {
5342 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5343 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5344 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5345 mTouchStatistics.reset();
5346 }
5347 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5348 mTouchStatistics.addValue(latencyMicros);
5349}
5350
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351void InputDispatcher::traceInboundQueueLengthLocked() {
5352 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005353 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 }
5355}
5356
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005357void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 if (ATRACE_ENABLED()) {
5359 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005360 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005361 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 }
5363}
5364
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005365void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 if (ATRACE_ENABLED()) {
5367 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005368 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005369 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371}
5372
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005373void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005376 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 dumpDispatchStateLocked(dump);
5378
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005379 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005380 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005381 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
5383}
5384
5385void InputDispatcher::monitor() {
5386 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005387 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005389 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390}
5391
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005392/**
5393 * Wake up the dispatcher and wait until it processes all events and commands.
5394 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5395 * this method can be safely called from any thread, as long as you've ensured that
5396 * the work you are interested in completing has already been queued.
5397 */
5398bool InputDispatcher::waitForIdle() {
5399 /**
5400 * Timeout should represent the longest possible time that a device might spend processing
5401 * events and commands.
5402 */
5403 constexpr std::chrono::duration TIMEOUT = 100ms;
5404 std::unique_lock lock(mLock);
5405 mLooper->wake();
5406 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5407 return result == std::cv_status::no_timeout;
5408}
5409
Vishnu Naire798b472020-07-23 13:52:21 -07005410/**
5411 * Sets focus to the window identified by the token. This must be called
5412 * after updating any input window handles.
5413 *
5414 * Params:
5415 * request.token - input channel token used to identify the window that should gain focus.
5416 * request.focusedToken - the token that the caller expects currently to be focused. If the
5417 * specified token does not match the currently focused window, this request will be dropped.
5418 * If the specified focused token matches the currently focused window, the call will succeed.
5419 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5420 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5421 * when requesting the focus change. This determines which request gets
5422 * precedence if there is a focus change request from another source such as pointer down.
5423 */
Vishnu Nair958da932020-08-21 17:12:37 -07005424void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5425 { // acquire lock
5426 std::scoped_lock _l(mLock);
5427
5428 const int32_t displayId = request.displayId;
5429 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5430 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5431 ALOGD_IF(DEBUG_FOCUS,
5432 "setFocusedWindow on display %" PRId32
5433 " ignored, reason: focusedToken is not focused",
5434 displayId);
5435 return;
5436 }
5437
5438 mPendingFocusRequests.erase(displayId);
5439 FocusResult result = handleFocusRequestLocked(request);
5440 if (result == FocusResult::NOT_VISIBLE) {
5441 // The requested window is not currently visible. Wait for the window to become visible
5442 // and then provide it focus. This is to handle situations where a user action triggers
5443 // a new window to appear. We want to be able to queue any key events after the user
5444 // action and deliver it to the newly focused window. In order for this to happen, we
5445 // take focus from the currently focused window so key events can be queued.
5446 ALOGD_IF(DEBUG_FOCUS,
5447 "setFocusedWindow on display %" PRId32
5448 " pending, reason: window is not visible",
5449 displayId);
5450 mPendingFocusRequests[displayId] = request;
5451 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5452 "setFocusedWindow_AwaitingWindowVisibility");
5453 } else if (result != FocusResult::OK) {
5454 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5455 typeToString(result));
5456 }
5457 } // release lock
5458 // Wake up poll loop since it may need to make new input dispatching choices.
5459 mLooper->wake();
5460}
5461
5462InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5463 const FocusRequest& request) {
5464 const int32_t displayId = request.displayId;
5465 const sp<IBinder> newFocusedToken = request.token;
5466 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5467
5468 if (oldFocusedToken == request.token) {
5469 ALOGD_IF(DEBUG_FOCUS,
5470 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5471 displayId);
5472 return FocusResult::OK;
5473 }
5474
5475 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5476 if (result != FocusResult::OK) {
5477 return result;
5478 }
5479
5480 std::string_view reason =
5481 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5482 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5483 return FocusResult::OK;
5484}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005485
Vishnu Nairad321cd2020-08-20 16:40:21 -07005486void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5487 const sp<IBinder>& newFocusedToken, int32_t displayId,
5488 std::string_view reason) {
5489 if (oldFocusedToken) {
5490 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005491 if (focusedInputChannel) {
5492 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5493 "focus left window");
5494 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005495 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005496 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005497 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005498 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005499 if (newFocusedToken) {
5500 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5501 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005502 }
5503
5504 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005505 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005506 }
5507}
Vishnu Nair958da932020-08-21 17:12:37 -07005508
5509/**
5510 * Checks if the window token can be focused on a display. The token can be focused if there is
5511 * at least one window handle that is visible with the same token and all window handles with the
5512 * same token are focusable.
5513 *
5514 * In the case of mirroring, two windows may share the same window token and their visibility
5515 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5516 * we expect the focusability of the windows to match since its hard to reason why one window can
5517 * receive focus events and the other cannot when both are backed by the same input channel.
5518 */
5519InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5520 int32_t displayId) const {
5521 bool allWindowsAreFocusable = true;
5522 bool visibleWindowFound = false;
5523 bool windowFound = false;
5524 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5525 if (window->getToken() != token) {
5526 continue;
5527 }
5528 windowFound = true;
5529 if (window->getInfo()->visible) {
5530 // Check if at least a single window is visible.
5531 visibleWindowFound = true;
5532 }
5533 if (!window->getInfo()->focusable) {
5534 // Check if all windows with the window token are focusable.
5535 allWindowsAreFocusable = false;
5536 break;
5537 }
5538 }
5539
5540 if (!windowFound) {
5541 return FocusResult::NO_WINDOW;
5542 }
5543 if (!allWindowsAreFocusable) {
5544 return FocusResult::NOT_FOCUSABLE;
5545 }
5546 if (!visibleWindowFound) {
5547 return FocusResult::NOT_VISIBLE;
5548 }
5549
5550 return FocusResult::OK;
5551}
Garfield Tane84e6f92019-08-29 17:28:41 -07005552} // namespace android::inputdispatcher