blob: b480ae44ee7ae122343e53136973e5e5fc4a3975 [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);
1776 // The order of the operands in the 'if' below is important because even if the feature
1777 // is not BLOCK we want isTouchTrustedLocked() to execute in order to log details to
1778 // logcat.
1779 if (!isTouchTrustedLocked(occlusionInfo) &&
1780 mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1781 ALOGW("Dropping untrusted touch event due to %s/%d",
1782 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1783 newTouchedWindowHandle = nullptr;
1784 }
1785 }
1786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 // Also don't send the new touch event to unresponsive gesture monitors
1788 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1789
Michael Wright3dd60e22019-03-27 22:06:44 +00001790 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1791 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 "(%d, %d) in display %" PRId32 ".",
1793 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001794 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001795 goto Failed;
1796 }
1797
1798 if (newTouchedWindowHandle != nullptr) {
1799 // Set target flags.
1800 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1801 if (isSplit) {
1802 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1805 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1806 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1807 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1808 }
1809
1810 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001811 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1812 newHoverWindowHandle = nullptr;
1813 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001814 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 }
1816
1817 // Update the temporary touch state.
1818 BitSet32 pointerIds;
1819 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001820 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001821 pointerIds.markBit(pointerId);
1822 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 } else {
1828 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1829
1830 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001831 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001832 if (DEBUG_FOCUS) {
1833 ALOGD("Dropping event because the pointer is not down or we previously "
1834 "dropped the pointer down event in display %" PRId32,
1835 displayId);
1836 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 goto Failed;
1839 }
1840
1841 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001842 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001844 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1845 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001848 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001849 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001850 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1851 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001852 if (DEBUG_FOCUS) {
1853 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1854 oldTouchedWindowHandle->getName().c_str(),
1855 newTouchedWindowHandle->getName().c_str(), displayId);
1856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001858 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1859 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1860 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
1862 // Make a slippery entrance into the new window.
1863 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1864 isSplit = true;
1865 }
1866
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 int32_t targetFlags =
1868 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 if (isSplit) {
1870 targetFlags |= InputTarget::FLAG_SPLIT;
1871 }
1872 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1873 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1874 }
1875
1876 BitSet32 pointerIds;
1877 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001878 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001880 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882 }
1883 }
1884
1885 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001886 // Let the previous window know that the hover sequence is over, unless we already did it
1887 // when dispatching it as is to newTouchedWindowHandle.
1888 if (mLastHoverWindowHandle != nullptr &&
1889 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1890 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891#if DEBUG_HOVER
1892 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001895 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1896 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Garfield Tandf26e862020-07-01 20:18:19 -07001899 // Let the new window know that the hover sequence is starting, unless we already did it
1900 // when dispatching it as is to newTouchedWindowHandle.
1901 if (newHoverWindowHandle != nullptr &&
1902 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1903 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904#if DEBUG_HOVER
1905 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001906 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001908 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1909 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1910 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912 }
1913
1914 // Check permission to inject into all touched foreground windows and ensure there
1915 // is at least one touched foreground window.
1916 {
1917 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1920 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001921 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001922 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 injectionPermission = INJECTION_PERMISSION_DENIED;
1924 goto Failed;
1925 }
1926 }
1927 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001928 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001929 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001930 ALOGI("Dropping event because there is no touched foreground window in display "
1931 "%" PRId32 " or gesture monitor to receive it.",
1932 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 goto Failed;
1935 }
1936
1937 // Permission granted to injection into all touched foreground windows.
1938 injectionPermission = INJECTION_PERMISSION_GRANTED;
1939 }
1940
1941 // Check whether windows listening for outside touches are owned by the same UID. If it is
1942 // set the policy flag that we will not reveal coordinate information to this window.
1943 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1944 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001945 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001946 if (foregroundWindowHandle) {
1947 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001948 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001949 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1950 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1951 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1953 InputTarget::FLAG_ZERO_COORDS,
1954 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 }
1957 }
1958 }
1959 }
1960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 // If this is the first pointer going down and the touched window has a wallpaper
1962 // then also add the touched wallpaper windows so they are locked in for the duration
1963 // of the touch gesture.
1964 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1965 // engine only supports touch events. We would need to add a mechanism similar
1966 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1967 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1968 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001969 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001971 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001972 getWindowHandlesLocked(displayId);
1973 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001975 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001976 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001977 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001978 .addOrUpdateWindow(windowHandle,
1979 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1980 InputTarget::
1981 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1982 InputTarget::FLAG_DISPATCH_AS_IS,
1983 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
1985 }
1986 }
1987 }
1988
1989 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001994 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 }
1996
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001998 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001999 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 }
2001
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 // Drop the outside or hover touch windows since we will not care about them
2003 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002004 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
2006Failed:
2007 // Check injection permission once and for all.
2008 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 injectionPermission = INJECTION_PERMISSION_GRANTED;
2011 } else {
2012 injectionPermission = INJECTION_PERMISSION_DENIED;
2013 }
2014 }
2015
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002016 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2017 return injectionResult;
2018 }
2019
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002021 if (!wrongDevice) {
2022 if (switchedDevice) {
2023 if (DEBUG_FOCUS) {
2024 ALOGD("Conflicting pointer actions: Switched to a different device.");
2025 }
2026 *outConflictingPointerActions = true;
2027 }
2028
2029 if (isHoverAction) {
2030 // Started hovering, therefore no longer down.
2031 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002032 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002033 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2034 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 *outConflictingPointerActions = true;
2037 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002038 tempTouchState.reset();
2039 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2040 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2041 tempTouchState.deviceId = entry.deviceId;
2042 tempTouchState.source = entry.source;
2043 tempTouchState.displayId = displayId;
2044 }
2045 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2046 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2047 // All pointers up or canceled.
2048 tempTouchState.reset();
2049 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2050 // First pointer went down.
2051 if (oldState && oldState->down) {
2052 if (DEBUG_FOCUS) {
2053 ALOGD("Conflicting pointer actions: Down received while already down.");
2054 }
2055 *outConflictingPointerActions = true;
2056 }
2057 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2058 // One pointer went up.
2059 if (isSplit) {
2060 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2061 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002063 for (size_t i = 0; i < tempTouchState.windows.size();) {
2064 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2065 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2066 touchedWindow.pointerIds.clearBit(pointerId);
2067 if (touchedWindow.pointerIds.isEmpty()) {
2068 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2069 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002072 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002074 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002075 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002076
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002077 // Save changes unless the action was scroll in which case the temporary touch
2078 // state was only valid for this one action.
2079 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2080 if (tempTouchState.displayId >= 0) {
2081 mTouchStatesByDisplay[displayId] = tempTouchState;
2082 } else {
2083 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002087 // Update hover state.
2088 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 return injectionResult;
2092}
2093
2094void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 int32_t targetFlags, BitSet32 pointerIds,
2096 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002097 std::vector<InputTarget>::iterator it =
2098 std::find_if(inputTargets.begin(), inputTargets.end(),
2099 [&windowHandle](const InputTarget& inputTarget) {
2100 return inputTarget.inputChannel->getConnectionToken() ==
2101 windowHandle->getToken();
2102 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002103
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002104 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002105
2106 if (it == inputTargets.end()) {
2107 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002108 std::shared_ptr<InputChannel> inputChannel =
2109 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002110 if (inputChannel == nullptr) {
2111 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2112 return;
2113 }
2114 inputTarget.inputChannel = inputChannel;
2115 inputTarget.flags = targetFlags;
2116 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2117 inputTargets.push_back(inputTarget);
2118 it = inputTargets.end() - 1;
2119 }
2120
2121 ALOG_ASSERT(it->flags == targetFlags);
2122 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2123
chaviw1ff3d1e2020-07-01 15:53:47 -07002124 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125}
2126
Michael Wright3dd60e22019-03-27 22:06:44 +00002127void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002128 int32_t displayId, float xOffset,
2129 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2131 mGlobalMonitorsByDisplay.find(displayId);
2132
2133 if (it != mGlobalMonitorsByDisplay.end()) {
2134 const std::vector<Monitor>& monitors = it->second;
2135 for (const Monitor& monitor : monitors) {
2136 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139}
2140
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2142 float yOffset,
2143 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 InputTarget target;
2145 target.inputChannel = monitor.inputChannel;
2146 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002147 ui::Transform t;
2148 t.set(xOffset, yOffset);
2149 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 inputTargets.push_back(target);
2151}
2152
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 const InjectionState* injectionState) {
2155 if (injectionState &&
2156 (windowHandle == nullptr ||
2157 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2158 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002159 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002161 "owned by uid %d",
2162 injectionState->injectorPid, injectionState->injectorUid,
2163 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 } else {
2165 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
2168 return false;
2169 }
2170 return true;
2171}
2172
Robert Carrc9bf1d32020-04-13 17:21:08 -07002173/**
2174 * Indicate whether one window handle should be considered as obscuring
2175 * another window handle. We only check a few preconditions. Actually
2176 * checking the bounds is left to the caller.
2177 */
2178static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2179 const sp<InputWindowHandle>& otherHandle) {
2180 // Compare by token so cloned layers aren't counted
2181 if (haveSameToken(windowHandle, otherHandle)) {
2182 return false;
2183 }
2184 auto info = windowHandle->getInfo();
2185 auto otherInfo = otherHandle->getInfo();
2186 if (!otherInfo->visible) {
2187 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002188 } else if (info->ownerUid == otherInfo->ownerUid) {
2189 // If ownerUid is the same we don't generate occlusion events as there
2190 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002191 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002192 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002193 return false;
2194 } else if (otherInfo->displayId != info->displayId) {
2195 return false;
2196 }
2197 return true;
2198}
2199
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002200/**
2201 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2202 * untrusted, one should check:
2203 *
2204 * 1. If result.hasBlockingOcclusion is true.
2205 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2206 * BLOCK_UNTRUSTED.
2207 *
2208 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2209 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2210 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2211 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2212 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2213 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2214 *
2215 * If neither of those is true, then it means the touch can be allowed.
2216 */
2217InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2218 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
2219 int32_t displayId = windowHandle->getInfo()->displayId;
2220 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2221 TouchOcclusionInfo info;
2222 info.hasBlockingOcclusion = false;
2223 info.obscuringOpacity = 0;
2224 info.obscuringUid = -1;
2225 std::map<int32_t, float> opacityByUid;
2226 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2227 if (windowHandle == otherHandle) {
2228 break; // All future windows are below us. Exit early.
2229 }
2230 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2231 if (canBeObscuredBy(windowHandle, otherHandle) &&
2232 windowHandle->getInfo()->ownerUid != otherInfo->ownerUid &&
2233 otherInfo->frameContainsPoint(x, y)) {
2234 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2235 // we perform the checks below to see if the touch can be propagated or not based on the
2236 // window's touch occlusion mode
2237 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2238 info.hasBlockingOcclusion = true;
2239 info.obscuringUid = otherInfo->ownerUid;
2240 info.obscuringPackage = otherInfo->packageName;
2241 break;
2242 }
2243 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2244 uint32_t uid = otherInfo->ownerUid;
2245 float opacity =
2246 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2247 // Given windows A and B:
2248 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2249 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2250 opacityByUid[uid] = opacity;
2251 if (opacity > info.obscuringOpacity) {
2252 info.obscuringOpacity = opacity;
2253 info.obscuringUid = uid;
2254 info.obscuringPackage = otherInfo->packageName;
2255 }
2256 }
2257 }
2258 }
2259 return info;
2260}
2261
2262bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2263 if (occlusionInfo.hasBlockingOcclusion) {
2264 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2265 occlusionInfo.obscuringUid);
2266 return false;
2267 }
2268 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2269 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2270 "%.2f, maximum allowed = %.2f)",
2271 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2272 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2273 return false;
2274 }
2275 return true;
2276}
2277
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2279 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002281 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002282 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002283 if (windowHandle == otherHandle) {
2284 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002287 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002288 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 return true;
2290 }
2291 }
2292 return false;
2293}
2294
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002295bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2296 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002297 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002298 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002299 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002300 if (windowHandle == otherHandle) {
2301 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002302 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002303 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002304 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002305 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002306 return true;
2307 }
2308 }
2309 return false;
2310}
2311
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002312std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002313 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002315 if (applicationHandle != nullptr) {
2316 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002317 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 } else {
2319 return applicationHandle->getName();
2320 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002321 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002322 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002324 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326}
2327
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002329 if (eventEntry.type == EventEntry::Type::FOCUS) {
2330 // Focus events are passed to apps, but do not represent user activity.
2331 return;
2332 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002333 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002334 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002335 if (focusedWindowHandle != nullptr) {
2336 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002337 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002339 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340#endif
2341 return;
2342 }
2343 }
2344
2345 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002346 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002347 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2349 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 return;
2351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002353 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 eventType = USER_ACTIVITY_EVENT_TOUCH;
2355 }
2356 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002358 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2360 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 return;
2362 }
2363 eventType = USER_ACTIVITY_EVENT_BUTTON;
2364 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002366 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002367 case EventEntry::Type::CONFIGURATION_CHANGED:
2368 case EventEntry::Type::DEVICE_RESET: {
2369 LOG_ALWAYS_FATAL("%s events are not user activity",
2370 EventEntry::typeToString(eventEntry.type));
2371 break;
2372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002375 std::unique_ptr<CommandEntry> commandEntry =
2376 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002377 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002379 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380}
2381
2382void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 const sp<Connection>& connection,
2384 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002385 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002386 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002388 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002389 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002390 ATRACE_NAME(message.c_str());
2391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
2393 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002394 "globalScaleFactor=%f, pointerIds=0x%x %s",
2395 connection->getInputChannelName().c_str(), inputTarget.flags,
2396 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2397 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398#endif
2399
2400 // Skip this event if the connection status is not normal.
2401 // We don't want to enqueue additional outbound events if the connection is broken.
2402 if (connection->status != Connection::STATUS_NORMAL) {
2403#if DEBUG_DISPATCH_CYCLE
2404 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002405 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406#endif
2407 return;
2408 }
2409
2410 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002411 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2412 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2413 "Entry type %s should not have FLAG_SPLIT",
2414 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002416 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002417 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002418 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002419 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 if (!splitMotionEntry) {
2421 return; // split event was dropped
2422 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002423 if (DEBUG_FOCUS) {
2424 ALOGD("channel '%s' ~ Split motion event.",
2425 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002426 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 splitMotionEntry->release();
2430 return;
2431 }
2432 }
2433
2434 // Not splitting. Enqueue dispatch entries for the event as is.
2435 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2436}
2437
2438void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002439 const sp<Connection>& connection,
2440 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002441 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002442 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002443 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002444 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002445 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 ATRACE_NAME(message.c_str());
2447 }
2448
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002449 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450
2451 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002452 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002453 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002454 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002456 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002458 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002460 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002462 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464
2465 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002466 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 startDispatchCycleLocked(currentTime, connection);
2468 }
2469}
2470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2472 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002473 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002475 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2477 connection->getInputChannelName().c_str(),
2478 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002479 ATRACE_NAME(message.c_str());
2480 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002481 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 if (!(inputTargetFlags & dispatchMode)) {
2483 return;
2484 }
2485 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2486
2487 // This is a new event.
2488 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002489 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002490 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002492 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2493 // different EventEntry than what was passed in.
2494 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002496 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002497 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002498 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002499 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002500 dispatchEntry->resolvedAction = keyEntry.action;
2501 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2504 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2507 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 return; // skip the inconsistent event
2510 }
2511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002514 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002515 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002516 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2517 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2518 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2519 static_cast<int32_t>(IdGenerator::Source::OTHER);
2520 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002521 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2522 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2523 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2524 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2525 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2526 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2527 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2528 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2529 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2530 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2531 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002533 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 }
2535 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002536 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2537 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2540 "event",
2541 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002546 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2548 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2549 }
2550 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2551 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2555 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2558 "event",
2559 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 return; // skip the inconsistent event
2562 }
2563
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002564 dispatchEntry->resolvedEventId =
2565 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2566 ? mIdGenerator.nextId()
2567 : motionEntry.id;
2568 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2569 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2570 ") to MotionEvent(id=0x%" PRIx32 ").",
2571 motionEntry.id, dispatchEntry->resolvedEventId);
2572 ATRACE_NAME(message.c_str());
2573 }
2574
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002575 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002576 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577
2578 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002580 case EventEntry::Type::FOCUS: {
2581 break;
2582 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002583 case EventEntry::Type::CONFIGURATION_CHANGED:
2584 case EventEntry::Type::DEVICE_RESET: {
2585 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002586 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002587 break;
2588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590
2591 // Remember that we are waiting for this dispatch to complete.
2592 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002593 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 }
2595
2596 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002597 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002598 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002599}
2600
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002601/**
2602 * This function is purely for debugging. It helps us understand where the user interaction
2603 * was taking place. For example, if user is touching launcher, we will see a log that user
2604 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2605 * We will see both launcher and wallpaper in that list.
2606 * Once the interaction with a particular set of connections starts, no new logs will be printed
2607 * until the set of interacted connections changes.
2608 *
2609 * The following items are skipped, to reduce the logspam:
2610 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2611 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2612 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2613 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2614 * Both of those ACTION_UP events would not be logged
2615 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2616 * will not be logged. This is omitted to reduce the amount of data printed.
2617 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2618 * gesture monitor is the only connection receiving the remainder of the gesture.
2619 */
2620void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2621 const std::vector<InputTarget>& targets) {
2622 // Skip ACTION_UP events, and all events other than keys and motions
2623 if (entry.type == EventEntry::Type::KEY) {
2624 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2625 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2626 return;
2627 }
2628 } else if (entry.type == EventEntry::Type::MOTION) {
2629 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2630 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2631 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2632 return;
2633 }
2634 } else {
2635 return; // Not a key or a motion
2636 }
2637
2638 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2639 std::vector<sp<Connection>> newConnections;
2640 for (const InputTarget& target : targets) {
2641 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2642 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2643 continue; // Skip windows that receive ACTION_OUTSIDE
2644 }
2645
2646 sp<IBinder> token = target.inputChannel->getConnectionToken();
2647 sp<Connection> connection = getConnectionLocked(token);
2648 if (connection == nullptr || connection->monitor) {
2649 continue; // We only need to keep track of the non-monitor connections.
2650 }
2651 newConnectionTokens.insert(std::move(token));
2652 newConnections.emplace_back(connection);
2653 }
2654 if (newConnectionTokens == mInteractionConnectionTokens) {
2655 return; // no change
2656 }
2657 mInteractionConnectionTokens = newConnectionTokens;
2658
2659 std::string windowList;
2660 for (const sp<Connection>& connection : newConnections) {
2661 windowList += connection->getWindowName() + ", ";
2662 }
2663 std::string message = "Interaction with windows: " + windowList;
2664 if (windowList.empty()) {
2665 message += "<none>";
2666 }
2667 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2668}
2669
chaviwfd6d3512019-03-25 13:23:49 -07002670void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002671 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002672 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002673 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2674 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002675 return;
2676 }
2677
Vishnu Nairad321cd2020-08-20 16:40:21 -07002678 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2679 if (focusedToken == token) {
2680 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002681 return;
2682 }
2683
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002684 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2685 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002686 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002687 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688}
2689
2690void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002692 if (ATRACE_ENABLED()) {
2693 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002695 ATRACE_NAME(message.c_str());
2696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002698 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699#endif
2700
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002701 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2702 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002704 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002705 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002706 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707
2708 // Publish the event.
2709 status_t status;
2710 EventEntry* eventEntry = dispatchEntry->eventEntry;
2711 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002712 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002713 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2714 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002716 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002717 status =
2718 connection->inputPublisher
2719 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2720 keyEntry->deviceId, keyEntry->source,
2721 keyEntry->displayId, std::move(hmac),
2722 dispatchEntry->resolvedAction,
2723 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2724 keyEntry->scanCode, keyEntry->metaState,
2725 keyEntry->repeatCount, keyEntry->downTime,
2726 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
2729
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002730 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 PointerCoords scaledCoords[MAX_POINTERS];
2734 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2735
chaviw82357092020-01-28 13:13:06 -08002736 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2738 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2739 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002740 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2742 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002743 // Don't apply window scale here since we don't want scale to affect raw
2744 // coordinates. The scale will be sent back to the client and applied
2745 // later when requesting relative coordinates.
2746 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2747 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002748 }
2749 usingCoords = scaledCoords;
2750 }
2751 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 // We don't want the dispatch target to know.
2753 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2754 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2755 scaledCoords[i].clear();
2756 }
2757 usingCoords = scaledCoords;
2758 }
2759 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002760
2761 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762
2763 // Publish the motion event.
2764 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002765 .publishMotionEvent(dispatchEntry->seq,
2766 dispatchEntry->resolvedEventId,
2767 motionEntry->deviceId, motionEntry->source,
2768 motionEntry->displayId, std::move(hmac),
2769 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770 motionEntry->actionButton,
2771 dispatchEntry->resolvedFlags,
2772 motionEntry->edgeFlags, motionEntry->metaState,
2773 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002774 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002775 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002776 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 motionEntry->yPrecision,
2778 motionEntry->xCursorPosition,
2779 motionEntry->yCursorPosition,
2780 motionEntry->downTime, motionEntry->eventTime,
2781 motionEntry->pointerCount,
2782 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002783 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 break;
2785 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002786 case EventEntry::Type::FOCUS: {
2787 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2788 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002789 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002790 focusEntry->hasFocus,
2791 mInTouchMode);
2792 break;
2793 }
2794
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002795 case EventEntry::Type::CONFIGURATION_CHANGED:
2796 case EventEntry::Type::DEVICE_RESET: {
2797 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2798 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002799 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 }
2802
2803 // Check the result.
2804 if (status) {
2805 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002806 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 "This is unexpected because the wait queue is empty, so the pipe "
2809 "should be empty and we shouldn't have any problems writing an "
2810 "event to it, status=%d",
2811 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2813 } else {
2814 // Pipe is full and we are waiting for the app to finish process some events
2815 // before sending more events to it.
2816#if DEBUG_DISPATCH_CYCLE
2817 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 "waiting for the application to catch up",
2819 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
2822 } else {
2823 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 "status=%d",
2825 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2827 }
2828 return;
2829 }
2830
2831 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002832 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2833 connection->outboundQueue.end(),
2834 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002835 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002836 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002837 if (connection->responsive) {
2838 mAnrTracker.insert(dispatchEntry->timeoutTime,
2839 connection->inputChannel->getConnectionToken());
2840 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002841 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
2843}
2844
chaviw09c8d2d2020-08-24 15:48:26 -07002845std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2846 size_t size;
2847 switch (event.type) {
2848 case VerifiedInputEvent::Type::KEY: {
2849 size = sizeof(VerifiedKeyEvent);
2850 break;
2851 }
2852 case VerifiedInputEvent::Type::MOTION: {
2853 size = sizeof(VerifiedMotionEvent);
2854 break;
2855 }
2856 }
2857 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2858 return mHmacKeyManager.sign(start, size);
2859}
2860
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002861const std::array<uint8_t, 32> InputDispatcher::getSignature(
2862 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2863 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2864 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2865 // Only sign events up and down events as the purely move events
2866 // are tied to their up/down counterparts so signing would be redundant.
2867 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2868 verifiedEvent.actionMasked = actionMasked;
2869 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002870 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002871 }
2872 return INVALID_HMAC;
2873}
2874
2875const std::array<uint8_t, 32> InputDispatcher::getSignature(
2876 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2877 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2878 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2879 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002880 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002881}
2882
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 const sp<Connection>& connection, uint32_t seq,
2885 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#if DEBUG_DISPATCH_CYCLE
2887 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889#endif
2890
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 if (connection->status == Connection::STATUS_BROKEN ||
2892 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 return;
2894 }
2895
2896 // Notify other system components and prepare to start the next dispatch cycle.
2897 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2898}
2899
2900void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 const sp<Connection>& connection,
2902 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903#if DEBUG_DISPATCH_CYCLE
2904 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906#endif
2907
2908 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002909 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002910 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002911 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002912 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913
2914 // The connection appears to be unrecoverably broken.
2915 // Ignore already broken or zombie connections.
2916 if (connection->status == Connection::STATUS_NORMAL) {
2917 connection->status = Connection::STATUS_BROKEN;
2918
2919 if (notify) {
2920 // Notify other system components.
2921 onDispatchCycleBrokenLocked(currentTime, connection);
2922 }
2923 }
2924}
2925
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002926void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2927 while (!queue.empty()) {
2928 DispatchEntry* dispatchEntry = queue.front();
2929 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002930 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932}
2933
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002934void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002936 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
2938 delete dispatchEntry;
2939}
2940
2941int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2942 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2943
2944 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002945 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002947 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 "fd=%d, events=0x%x",
2950 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 return 0; // remove the callback
2952 }
2953
2954 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002955 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2957 if (!(events & ALOOPER_EVENT_INPUT)) {
2958 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 "events=0x%x",
2960 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 return 1;
2962 }
2963
2964 nsecs_t currentTime = now();
2965 bool gotOne = false;
2966 status_t status;
2967 for (;;) {
2968 uint32_t seq;
2969 bool handled;
2970 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2971 if (status) {
2972 break;
2973 }
2974 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2975 gotOne = true;
2976 }
2977 if (gotOne) {
2978 d->runCommandsLockedInterruptible();
2979 if (status == WOULD_BLOCK) {
2980 return 1;
2981 }
2982 }
2983
2984 notify = status != DEAD_OBJECT || !connection->monitor;
2985 if (notify) {
2986 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
2989 } else {
2990 // Monitor channels are never explicitly unregistered.
2991 // We do it automatically when the remote endpoint is closed so don't warn
2992 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002993 const bool stillHaveWindowHandle =
2994 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2995 nullptr;
2996 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 if (notify) {
2998 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 "events=0x%x",
3000 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 }
3002 }
3003
Garfield Tan15601662020-09-22 15:32:38 -07003004 // Remove the channel.
3005 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008}
3009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003012 for (const auto& pair : mConnectionsByFd) {
3013 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
3015}
3016
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003018 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003019 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3020 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3021}
3022
3023void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3024 const CancelationOptions& options,
3025 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3026 for (const auto& it : monitorsByDisplay) {
3027 const std::vector<Monitor>& monitors = it.second;
3028 for (const Monitor& monitor : monitors) {
3029 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003030 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003031 }
3032}
3033
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003035 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003036 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003037 if (connection == nullptr) {
3038 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003040
3041 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042}
3043
3044void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3045 const sp<Connection>& connection, const CancelationOptions& options) {
3046 if (connection->status == Connection::STATUS_BROKEN) {
3047 return;
3048 }
3049
3050 nsecs_t currentTime = now();
3051
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003052 std::vector<EventEntry*> cancelationEvents =
3053 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003055 if (cancelationEvents.empty()) {
3056 return;
3057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003059 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3060 "with reality: %s, mode=%d.",
3061 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3062 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003064
3065 InputTarget target;
3066 sp<InputWindowHandle> windowHandle =
3067 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3068 if (windowHandle != nullptr) {
3069 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003070 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003071 target.globalScaleFactor = windowInfo->globalScaleFactor;
3072 }
3073 target.inputChannel = connection->inputChannel;
3074 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3075
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003076 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3077 EventEntry* cancelationEventEntry = cancelationEvents[i];
3078 switch (cancelationEventEntry->type) {
3079 case EventEntry::Type::KEY: {
3080 logOutboundKeyDetails("cancel - ",
3081 static_cast<const KeyEntry&>(*cancelationEventEntry));
3082 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003084 case EventEntry::Type::MOTION: {
3085 logOutboundMotionDetails("cancel - ",
3086 static_cast<const MotionEntry&>(*cancelationEventEntry));
3087 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003089 case EventEntry::Type::FOCUS: {
3090 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3091 break;
3092 }
3093 case EventEntry::Type::CONFIGURATION_CHANGED:
3094 case EventEntry::Type::DEVICE_RESET: {
3095 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3096 EventEntry::typeToString(cancelationEventEntry->type));
3097 break;
3098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 }
3100
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003101 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3102 target, InputTarget::FLAG_DISPATCH_AS_IS);
3103
3104 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003106
3107 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108}
3109
Svet Ganov5d3bc372020-01-26 23:11:07 -08003110void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3111 const sp<Connection>& connection) {
3112 if (connection->status == Connection::STATUS_BROKEN) {
3113 return;
3114 }
3115
3116 nsecs_t currentTime = now();
3117
3118 std::vector<EventEntry*> downEvents =
3119 connection->inputState.synthesizePointerDownEvents(currentTime);
3120
3121 if (downEvents.empty()) {
3122 return;
3123 }
3124
3125#if DEBUG_OUTBOUND_EVENT_DETAILS
3126 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3127 connection->getInputChannelName().c_str(), downEvents.size());
3128#endif
3129
3130 InputTarget target;
3131 sp<InputWindowHandle> windowHandle =
3132 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3133 if (windowHandle != nullptr) {
3134 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003135 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003136 target.globalScaleFactor = windowInfo->globalScaleFactor;
3137 }
3138 target.inputChannel = connection->inputChannel;
3139 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3140
3141 for (EventEntry* downEventEntry : downEvents) {
3142 switch (downEventEntry->type) {
3143 case EventEntry::Type::MOTION: {
3144 logOutboundMotionDetails("down - ",
3145 static_cast<const MotionEntry&>(*downEventEntry));
3146 break;
3147 }
3148
3149 case EventEntry::Type::KEY:
3150 case EventEntry::Type::FOCUS:
3151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3154 EventEntry::typeToString(downEventEntry->type));
3155 break;
3156 }
3157 }
3158
3159 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3160 target, InputTarget::FLAG_DISPATCH_AS_IS);
3161
3162 downEventEntry->release();
3163 }
3164
3165 startDispatchCycleLocked(currentTime, connection);
3166}
3167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003168MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003169 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 ALOG_ASSERT(pointerIds.value != 0);
3171
3172 uint32_t splitPointerIndexMap[MAX_POINTERS];
3173 PointerProperties splitPointerProperties[MAX_POINTERS];
3174 PointerCoords splitPointerCoords[MAX_POINTERS];
3175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003176 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 uint32_t splitPointerCount = 0;
3178
3179 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003182 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 uint32_t pointerId = uint32_t(pointerProperties.id);
3184 if (pointerIds.hasBit(pointerId)) {
3185 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3186 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3187 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003188 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 splitPointerCount += 1;
3190 }
3191 }
3192
3193 if (splitPointerCount != pointerIds.count()) {
3194 // This is bad. We are missing some of the pointers that we expected to deliver.
3195 // Most likely this indicates that we received an ACTION_MOVE events that has
3196 // different pointer ids than we expected based on the previous ACTION_DOWN
3197 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3198 // in this way.
3199 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 "we expected there to be %d pointers. This probably means we received "
3201 "a broken sequence of pointer ids from the input device.",
3202 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003203 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3209 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3211 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003212 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 uint32_t pointerId = uint32_t(pointerProperties.id);
3214 if (pointerIds.hasBit(pointerId)) {
3215 if (pointerIds.count() == 1) {
3216 // The first/last pointer went down/up.
3217 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 ? AMOTION_EVENT_ACTION_DOWN
3219 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 } else {
3221 // A secondary pointer went down/up.
3222 uint32_t splitPointerIndex = 0;
3223 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3224 splitPointerIndex += 1;
3225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 action = maskedAction |
3227 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229 } else {
3230 // An unrelated pointer changed.
3231 action = AMOTION_EVENT_ACTION_MOVE;
3232 }
3233 }
3234
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 int32_t newId = mIdGenerator.nextId();
3236 if (ATRACE_ENABLED()) {
3237 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3238 ") to MotionEvent(id=0x%" PRIx32 ").",
3239 originalMotionEntry.id, newId);
3240 ATRACE_NAME(message.c_str());
3241 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003242 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003243 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3244 originalMotionEntry.source, originalMotionEntry.displayId,
3245 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003246 originalMotionEntry.actionButton, originalMotionEntry.flags,
3247 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3248 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3249 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3250 originalMotionEntry.xCursorPosition,
3251 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003252 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003254 if (originalMotionEntry.injectionState) {
3255 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 splitMotionEntry->injectionState->refCount += 1;
3257 }
3258
3259 return splitMotionEntry;
3260}
3261
3262void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3263#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003264 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#endif
3266
3267 bool needWake;
3268 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003269 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Prabir Pradhan42611e02018-11-27 14:04:02 -08003271 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003272 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 needWake = enqueueInboundEventLocked(newEntry);
3274 } // release lock
3275
3276 if (needWake) {
3277 mLooper->wake();
3278 }
3279}
3280
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003281/**
3282 * If one of the meta shortcuts is detected, process them here:
3283 * Meta + Backspace -> generate BACK
3284 * Meta + Enter -> generate HOME
3285 * This will potentially overwrite keyCode and metaState.
3286 */
3287void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003289 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3290 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3291 if (keyCode == AKEYCODE_DEL) {
3292 newKeyCode = AKEYCODE_BACK;
3293 } else if (keyCode == AKEYCODE_ENTER) {
3294 newKeyCode = AKEYCODE_HOME;
3295 }
3296 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003297 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003298 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003299 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003300 keyCode = newKeyCode;
3301 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3302 }
3303 } else if (action == AKEY_EVENT_ACTION_UP) {
3304 // In order to maintain a consistent stream of up and down events, check to see if the key
3305 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3306 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003307 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003308 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003309 auto replacementIt = mReplacedKeys.find(replacement);
3310 if (replacementIt != mReplacedKeys.end()) {
3311 keyCode = replacementIt->second;
3312 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003313 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3314 }
3315 }
3316}
3317
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3319#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3321 "policyFlags=0x%x, action=0x%x, "
3322 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3323 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3324 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3325 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326#endif
3327 if (!validateKeyEvent(args->action)) {
3328 return;
3329 }
3330
3331 uint32_t policyFlags = args->policyFlags;
3332 int32_t flags = args->flags;
3333 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003334 // InputDispatcher tracks and generates key repeats on behalf of
3335 // whatever notifies it, so repeatCount should always be set to 0
3336 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3338 policyFlags |= POLICY_FLAG_VIRTUAL;
3339 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 if (policyFlags & POLICY_FLAG_FUNCTION) {
3342 metaState |= AMETA_FUNCTION_ON;
3343 }
3344
3345 policyFlags |= POLICY_FLAG_TRUSTED;
3346
Michael Wright78f24442014-08-06 15:55:28 -07003347 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003348 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003349
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003351 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003352 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3353 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
Michael Wright2b3c3302018-03-02 17:19:13 +00003355 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003357 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3358 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 bool needWake;
3363 { // acquire lock
3364 mLock.lock();
3365
3366 if (shouldSendKeyToInputFilterLocked(args)) {
3367 mLock.unlock();
3368
3369 policyFlags |= POLICY_FLAG_FILTERED;
3370 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3371 return; // event was consumed by the filter
3372 }
3373
3374 mLock.lock();
3375 }
3376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003378 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 args->displayId, policyFlags, args->action, flags, keyCode,
3380 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
3382 needWake = enqueueInboundEventLocked(newEntry);
3383 mLock.unlock();
3384 } // release lock
3385
3386 if (needWake) {
3387 mLooper->wake();
3388 }
3389}
3390
3391bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3392 return mInputFilterEnabled;
3393}
3394
3395void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3396#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003397 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3398 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003399 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3400 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003401 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003402 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3403 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3404 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3405 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 for (uint32_t i = 0; i < args->pointerCount; i++) {
3407 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 "x=%f, y=%f, pressure=%f, size=%f, "
3409 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3410 "orientation=%f",
3411 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3412 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3413 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3414 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3415 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3416 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3417 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3418 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3419 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3420 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3424 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 return;
3426 }
3427
3428 uint32_t policyFlags = args->policyFlags;
3429 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003430
3431 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003432 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003433 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3434 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437
3438 bool needWake;
3439 { // acquire lock
3440 mLock.lock();
3441
3442 if (shouldSendMotionToInputFilterLocked(args)) {
3443 mLock.unlock();
3444
3445 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003446 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003447 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3448 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003449 args->metaState, args->buttonState, args->classification, transform,
3450 args->xPrecision, args->yPrecision, args->xCursorPosition,
3451 args->yCursorPosition, args->downTime, args->eventTime,
3452 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453
3454 policyFlags |= POLICY_FLAG_FILTERED;
3455 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3456 return; // event was consumed by the filter
3457 }
3458
3459 mLock.lock();
3460 }
3461
3462 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003463 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003464 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003465 args->displayId, policyFlags, args->action, args->actionButton,
3466 args->flags, args->metaState, args->buttonState,
3467 args->classification, args->edgeFlags, args->xPrecision,
3468 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3469 args->downTime, args->pointerCount, args->pointerProperties,
3470 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
3472 needWake = enqueueInboundEventLocked(newEntry);
3473 mLock.unlock();
3474 } // release lock
3475
3476 if (needWake) {
3477 mLooper->wake();
3478 }
3479}
3480
3481bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003482 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483}
3484
3485void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3486#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003487 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 "switchMask=0x%08x",
3489 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490#endif
3491
3492 uint32_t policyFlags = args->policyFlags;
3493 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003494 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495}
3496
3497void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3498#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3500 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501#endif
3502
3503 bool needWake;
3504 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003505 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Prabir Pradhan42611e02018-11-27 14:04:02 -08003507 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003508 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 needWake = enqueueInboundEventLocked(newEntry);
3510 } // release lock
3511
3512 if (needWake) {
3513 mLooper->wake();
3514 }
3515}
3516
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003517InputEventInjectionResult InputDispatcher::injectInputEvent(
3518 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3519 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#if DEBUG_INBOUND_EVENT_DETAILS
3521 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003522 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3523 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003525 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
3527 policyFlags |= POLICY_FLAG_INJECTED;
3528 if (hasInjectionPermission(injectorPid, injectorUid)) {
3529 policyFlags |= POLICY_FLAG_TRUSTED;
3530 }
3531
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003532 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003535 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3536 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003537 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003538 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003541 int32_t flags = incomingKey.getFlags();
3542 int32_t keyCode = incomingKey.getKeyCode();
3543 int32_t metaState = incomingKey.getMetaState();
3544 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003545 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003546 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003547 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003548 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3549 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3550 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003552 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3553 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003554 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555
3556 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3557 android::base::Timer t;
3558 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3559 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3560 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3561 std::to_string(t.duration().count()).c_str());
3562 }
3563 }
3564
3565 mLock.lock();
3566 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003567 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3568 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003569 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3570 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003571 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 injectedEntries.push(injectedEntry);
3573 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003576 case AINPUT_EVENT_TYPE_MOTION: {
3577 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3578 int32_t action = motionEvent->getAction();
3579 size_t pointerCount = motionEvent->getPointerCount();
3580 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3581 int32_t actionButton = motionEvent->getActionButton();
3582 int32_t displayId = motionEvent->getDisplayId();
3583 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003584 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585 }
3586
3587 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3588 nsecs_t eventTime = motionEvent->getEventTime();
3589 android::base::Timer t;
3590 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3591 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3592 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3593 std::to_string(t.duration().count()).c_str());
3594 }
3595 }
3596
3597 mLock.lock();
3598 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3599 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3600 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003601 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3602 motionEvent->getSource(), motionEvent->getDisplayId(),
3603 policyFlags, action, actionButton, motionEvent->getFlags(),
3604 motionEvent->getMetaState(), motionEvent->getButtonState(),
3605 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3606 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003607 motionEvent->getRawXCursorPosition(),
3608 motionEvent->getRawYCursorPosition(),
3609 motionEvent->getDownTime(), uint32_t(pointerCount),
3610 pointerProperties, samplePointerCoords,
3611 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 injectedEntries.push(injectedEntry);
3613 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3614 sampleEventTimes += 1;
3615 samplePointerCoords += pointerCount;
3616 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003617 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003618 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 motionEvent->getDisplayId(), policyFlags, action,
3620 actionButton, motionEvent->getFlags(),
3621 motionEvent->getMetaState(), motionEvent->getButtonState(),
3622 motionEvent->getClassification(),
3623 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3624 motionEvent->getYPrecision(),
3625 motionEvent->getRawXCursorPosition(),
3626 motionEvent->getRawYCursorPosition(),
3627 motionEvent->getDownTime(), uint32_t(pointerCount),
3628 pointerProperties, samplePointerCoords,
3629 motionEvent->getXOffset(), motionEvent->getYOffset());
3630 injectedEntries.push(nextInjectedEntry);
3631 }
3632 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003636 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003637 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639
3640 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003641 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 injectionState->injectionIsAsync = true;
3643 }
3644
3645 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003646 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
3648 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003649 while (!injectedEntries.empty()) {
3650 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3651 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653
3654 mLock.unlock();
3655
3656 if (needWake) {
3657 mLooper->wake();
3658 }
3659
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003660 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003662 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003664 if (syncMode == InputEventInjectionSync::NONE) {
3665 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 } else {
3667 for (;;) {
3668 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003669 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 break;
3671 }
3672
3673 nsecs_t remainingTimeout = endTime - now();
3674 if (remainingTimeout <= 0) {
3675#if DEBUG_INJECTION
3676 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003679 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 break;
3681 }
3682
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003683 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003686 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3687 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 while (injectionState->pendingForegroundDispatches != 0) {
3689#if DEBUG_INJECTION
3690 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003691 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692#endif
3693 nsecs_t remainingTimeout = endTime - now();
3694 if (remainingTimeout <= 0) {
3695#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003696 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3697 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 break;
3701 }
3702
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003703 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705 }
3706 }
3707
3708 injectionState->release();
3709 } // release lock
3710
3711#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003712 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003713 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714#endif
3715
3716 return injectionResult;
3717}
3718
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003719std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003720 std::array<uint8_t, 32> calculatedHmac;
3721 std::unique_ptr<VerifiedInputEvent> result;
3722 switch (event.getType()) {
3723 case AINPUT_EVENT_TYPE_KEY: {
3724 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3725 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3726 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003727 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003728 break;
3729 }
3730 case AINPUT_EVENT_TYPE_MOTION: {
3731 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3732 VerifiedMotionEvent verifiedMotionEvent =
3733 verifiedMotionEventFromMotionEvent(motionEvent);
3734 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003735 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003736 break;
3737 }
3738 default: {
3739 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3740 return nullptr;
3741 }
3742 }
3743 if (calculatedHmac == INVALID_HMAC) {
3744 return nullptr;
3745 }
3746 if (calculatedHmac != event.getHmac()) {
3747 return nullptr;
3748 }
3749 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003750}
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003753 return injectorUid == 0 ||
3754 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755}
3756
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003757void InputDispatcher::setInjectionResult(EventEntry* entry,
3758 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 InjectionState* injectionState = entry->injectionState;
3760 if (injectionState) {
3761#if DEBUG_INJECTION
3762 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 "injectorPid=%d, injectorUid=%d",
3764 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765#endif
3766
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003767 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 // Log the outcome since the injector did not wait for the injection result.
3769 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003770 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 ALOGV("Asynchronous input event injection succeeded.");
3772 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003773 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003774 ALOGW("Asynchronous input event injection failed.");
3775 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003776 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 ALOGW("Asynchronous input event injection permission denied.");
3778 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003779 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 ALOGW("Asynchronous input event injection timed out.");
3781 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003782 case InputEventInjectionResult::PENDING:
3783 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3784 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786 }
3787
3788 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003789 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
3791}
3792
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003793void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 InjectionState* injectionState = entry->injectionState;
3795 if (injectionState) {
3796 injectionState->pendingForegroundDispatches += 1;
3797 }
3798}
3799
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003800void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 InjectionState* injectionState = entry->injectionState;
3802 if (injectionState) {
3803 injectionState->pendingForegroundDispatches -= 1;
3804
3805 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003806 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808 }
3809}
3810
Vishnu Nairad321cd2020-08-20 16:40:21 -07003811const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003812 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003813 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3814 auto it = mWindowHandlesByDisplay.find(displayId);
3815 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003816}
3817
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003819 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003820 if (windowHandleToken == nullptr) {
3821 return nullptr;
3822 }
3823
Arthur Hungb92218b2018-08-14 12:00:21 +08003824 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003825 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003826 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003827 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003828 return windowHandle;
3829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003832 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833}
3834
Vishnu Nairad321cd2020-08-20 16:40:21 -07003835sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3836 int displayId) const {
3837 if (windowHandleToken == nullptr) {
3838 return nullptr;
3839 }
3840
3841 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3842 if (windowHandle->getToken() == windowHandleToken) {
3843 return windowHandle;
3844 }
3845 }
3846 return nullptr;
3847}
3848
3849sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3850 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3851 return getWindowHandleLocked(focusedToken, displayId);
3852}
3853
Mady Mellor017bcd12020-06-23 19:12:00 +00003854bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3855 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003856 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003857 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003858 if (handle->getId() == windowHandle->getId() &&
3859 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003860 if (windowHandle->getInfo()->displayId != it.first) {
3861 ALOGE("Found window %s in display %" PRId32
3862 ", but it should belong to display %" PRId32,
3863 windowHandle->getName().c_str(), it.first,
3864 windowHandle->getInfo()->displayId);
3865 }
3866 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 }
3869 }
3870 return false;
3871}
3872
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003873bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3874 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3875 const bool noInputChannel =
3876 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3877 if (connection != nullptr && noInputChannel) {
3878 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3879 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3880 return false;
3881 }
3882
3883 if (connection == nullptr) {
3884 if (!noInputChannel) {
3885 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3886 }
3887 return false;
3888 }
3889 if (!connection->responsive) {
3890 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3891 return false;
3892 }
3893 return true;
3894}
3895
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003896std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3897 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003898 size_t count = mInputChannelsByToken.count(token);
3899 if (count == 0) {
3900 return nullptr;
3901 }
3902 return mInputChannelsByToken.at(token);
3903}
3904
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003905void InputDispatcher::updateWindowHandlesForDisplayLocked(
3906 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3907 if (inputWindowHandles.empty()) {
3908 // Remove all handles on a display if there are no windows left.
3909 mWindowHandlesByDisplay.erase(displayId);
3910 return;
3911 }
3912
3913 // Since we compare the pointer of input window handles across window updates, we need
3914 // to make sure the handle object for the same window stays unchanged across updates.
3915 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003916 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003917 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003918 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003919 }
3920
3921 std::vector<sp<InputWindowHandle>> newHandles;
3922 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3923 if (!handle->updateInfo()) {
3924 // handle no longer valid
3925 continue;
3926 }
3927
3928 const InputWindowInfo* info = handle->getInfo();
3929 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3930 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3931 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003932 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3933 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3934 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003935 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003936 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003937 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003938 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003939 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003940 }
3941
3942 if (info->displayId != displayId) {
3943 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3944 handle->getName().c_str(), displayId, info->displayId);
3945 continue;
3946 }
3947
Robert Carredd13602020-04-13 17:24:34 -07003948 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3949 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003950 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003951 oldHandle->updateFrom(handle);
3952 newHandles.push_back(oldHandle);
3953 } else {
3954 newHandles.push_back(handle);
3955 }
3956 }
3957
3958 // Insert or replace
3959 mWindowHandlesByDisplay[displayId] = newHandles;
3960}
3961
Arthur Hung72d8dc32020-03-28 00:48:39 +00003962void InputDispatcher::setInputWindows(
3963 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3964 { // acquire lock
3965 std::scoped_lock _l(mLock);
3966 for (auto const& i : handlesPerDisplay) {
3967 setInputWindowsLocked(i.second, i.first);
3968 }
3969 }
3970 // Wake up poll loop since it may need to make new input dispatching choices.
3971 mLooper->wake();
3972}
3973
Arthur Hungb92218b2018-08-14 12:00:21 +08003974/**
3975 * Called from InputManagerService, update window handle list by displayId that can receive input.
3976 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3977 * If set an empty list, remove all handles from the specific display.
3978 * For focused handle, check if need to change and send a cancel event to previous one.
3979 * For removed handle, check if need to send a cancel event if already in touch.
3980 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003981void InputDispatcher::setInputWindowsLocked(
3982 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003983 if (DEBUG_FOCUS) {
3984 std::string windowList;
3985 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3986 windowList += iwh->getName() + " ";
3987 }
3988 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003991 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3992 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3993 const bool noInputWindow =
3994 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3995 if (noInputWindow && window->getToken() != nullptr) {
3996 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3997 window->getName().c_str());
3998 window->releaseChannel();
3999 }
4000 }
4001
Arthur Hung72d8dc32020-03-28 00:48:39 +00004002 // Copy old handles for release if they are no longer present.
4003 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Arthur Hung72d8dc32020-03-28 00:48:39 +00004005 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004006
Vishnu Nair958da932020-08-21 17:12:37 -07004007 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4008 if (mLastHoverWindowHandle &&
4009 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4010 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004011 mLastHoverWindowHandle = nullptr;
4012 }
4013
Vishnu Nair958da932020-08-21 17:12:37 -07004014 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4015 if (focusedToken) {
4016 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4017 if (result != FocusResult::OK) {
4018 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4019 }
4020 }
4021
4022 std::optional<FocusRequest> focusRequest =
4023 getOptionalValueByKey(mPendingFocusRequests, displayId);
4024 if (focusRequest) {
4025 // If the window from the pending request is now visible, provide it focus.
4026 FocusResult result = handleFocusRequestLocked(*focusRequest);
4027 if (result != FocusResult::NOT_VISIBLE) {
4028 // Drop the request if we were able to change the focus or we cannot change
4029 // it for another reason.
4030 mPendingFocusRequests.erase(displayId);
4031 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004034 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4035 mTouchStatesByDisplay.find(displayId);
4036 if (stateIt != mTouchStatesByDisplay.end()) {
4037 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004038 for (size_t i = 0; i < state.windows.size();) {
4039 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004040 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004041 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004042 ALOGD("Touched window was removed: %s in display %" PRId32,
4043 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004044 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004045 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004046 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4047 if (touchedInputChannel != nullptr) {
4048 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4049 "touched window was removed");
4050 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004052 state.windows.erase(state.windows.begin() + i);
4053 } else {
4054 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
4056 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004057 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004058
Arthur Hung72d8dc32020-03-28 00:48:39 +00004059 // Release information for windows that are no longer present.
4060 // This ensures that unused input channels are released promptly.
4061 // Otherwise, they might stick around until the window handle is destroyed
4062 // which might not happen until the next GC.
4063 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004064 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004065 if (DEBUG_FOCUS) {
4066 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004067 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004068 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004069 }
chaviw291d88a2019-02-14 10:33:58 -08004070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071}
4072
4073void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004074 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004075 if (DEBUG_FOCUS) {
4076 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4077 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4078 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004079 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004080 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Chris Yea209fde2020-07-22 13:54:51 -07004082 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004083 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004084
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004085 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4086 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004087 }
4088
Chris Yea209fde2020-07-22 13:54:51 -07004089 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004090 if (inputApplicationHandle != nullptr) {
4091 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4092 } else {
4093 mFocusedApplicationHandlesByDisplay.erase(displayId);
4094 }
4095
4096 // No matter what the old focused application was, stop waiting on it because it is
4097 // no longer focused.
4098 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 } // release lock
4100
4101 // Wake up poll loop since it may need to make new input dispatching choices.
4102 mLooper->wake();
4103}
4104
Tiger Huang721e26f2018-07-24 22:26:19 +08004105/**
4106 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4107 * the display not specified.
4108 *
4109 * We track any unreleased events for each window. If a window loses the ability to receive the
4110 * released event, we will send a cancel event to it. So when the focused display is changed, we
4111 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4112 * display. The display-specified events won't be affected.
4113 */
4114void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004115 if (DEBUG_FOCUS) {
4116 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4117 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004118 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004119 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004120
4121 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004122 sp<IBinder> oldFocusedWindowToken =
4123 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4124 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004125 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004126 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004127 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 CancelationOptions
4129 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4130 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004131 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004132 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4133 }
4134 }
4135 mFocusedDisplayId = displayId;
4136
Chris Ye3c2d6f52020-08-09 10:39:48 -07004137 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004138 sp<IBinder> newFocusedWindowToken =
4139 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4140 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004141
Vishnu Nairad321cd2020-08-20 16:40:21 -07004142 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004143 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004144 if (!mFocusedWindowTokenByDisplay.empty()) {
4145 ALOGE("But another display has a focused window\n%s",
4146 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004147 }
4148 }
4149 }
4150
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004151 if (DEBUG_FOCUS) {
4152 logDispatchStateLocked();
4153 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004154 } // release lock
4155
4156 // Wake up poll loop since it may need to make new input dispatching choices.
4157 mLooper->wake();
4158}
4159
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004161 if (DEBUG_FOCUS) {
4162 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165 bool changed;
4166 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004167 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
4169 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4170 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004171 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
4174 if (mDispatchEnabled && !enabled) {
4175 resetAndDropEverythingLocked("dispatcher is being disabled");
4176 }
4177
4178 mDispatchEnabled = enabled;
4179 mDispatchFrozen = frozen;
4180 changed = true;
4181 } else {
4182 changed = false;
4183 }
4184
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004185 if (DEBUG_FOCUS) {
4186 logDispatchStateLocked();
4187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 } // release lock
4189
4190 if (changed) {
4191 // Wake up poll loop since it may need to make new input dispatching choices.
4192 mLooper->wake();
4193 }
4194}
4195
4196void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004197 if (DEBUG_FOCUS) {
4198 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
4201 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004202 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
4204 if (mInputFilterEnabled == enabled) {
4205 return;
4206 }
4207
4208 mInputFilterEnabled = enabled;
4209 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4210 } // release lock
4211
4212 // Wake up poll loop since there might be work to do to drop everything.
4213 mLooper->wake();
4214}
4215
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004216void InputDispatcher::setInTouchMode(bool inTouchMode) {
4217 std::scoped_lock lock(mLock);
4218 mInTouchMode = inTouchMode;
4219}
4220
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004221void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4222 if (opacity < 0 || opacity > 1) {
4223 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4224 return;
4225 }
4226
4227 std::scoped_lock lock(mLock);
4228 mMaximumObscuringOpacityForTouch = opacity;
4229}
4230
4231void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4232 std::scoped_lock lock(mLock);
4233 mBlockUntrustedTouchesMode = mode;
4234}
4235
chaviwfbe5d9c2018-12-26 12:23:37 -08004236bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4237 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004238 if (DEBUG_FOCUS) {
4239 ALOGD("Trivial transfer to same window.");
4240 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004241 return true;
4242 }
4243
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004245 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246
chaviwfbe5d9c2018-12-26 12:23:37 -08004247 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4248 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004249 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004250 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 return false;
4252 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004253 if (DEBUG_FOCUS) {
4254 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4255 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004258 if (DEBUG_FOCUS) {
4259 ALOGD("Cannot transfer focus because windows are on different displays.");
4260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 return false;
4262 }
4263
4264 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004265 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4266 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004267 for (size_t i = 0; i < state.windows.size(); i++) {
4268 const TouchedWindow& touchedWindow = state.windows[i];
4269 if (touchedWindow.windowHandle == fromWindowHandle) {
4270 int32_t oldTargetFlags = touchedWindow.targetFlags;
4271 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004273 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 int32_t newTargetFlags = oldTargetFlags &
4276 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4277 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004278 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
Jeff Brownf086ddb2014-02-11 14:28:48 -08004280 found = true;
4281 goto Found;
4282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 }
4284 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004285 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004288 if (DEBUG_FOCUS) {
4289 ALOGD("Focus transfer failed because from window did not have focus.");
4290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 return false;
4292 }
4293
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004294 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4295 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004296 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004297 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004298 CancelationOptions
4299 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4300 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004302 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 }
4304
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004305 if (DEBUG_FOCUS) {
4306 logDispatchStateLocked();
4307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 } // release lock
4309
4310 // Wake up poll loop since it may need to make new input dispatching choices.
4311 mLooper->wake();
4312 return true;
4313}
4314
4315void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004316 if (DEBUG_FOCUS) {
4317 ALOGD("Resetting and dropping all events (%s).", reason);
4318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
4320 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4321 synthesizeCancelationEventsForAllConnectionsLocked(options);
4322
4323 resetKeyRepeatLocked();
4324 releasePendingEventLocked();
4325 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004326 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004328 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004329 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004331 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332}
4333
4334void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004335 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 dumpDispatchStateLocked(dump);
4337
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338 std::istringstream stream(dump);
4339 std::string line;
4340
4341 while (std::getline(stream, line, '\n')) {
4342 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344}
4345
Vishnu Nairad321cd2020-08-20 16:40:21 -07004346std::string InputDispatcher::dumpFocusedWindowsLocked() {
4347 if (mFocusedWindowTokenByDisplay.empty()) {
4348 return INDENT "FocusedWindows: <none>\n";
4349 }
4350
4351 std::string dump;
4352 dump += INDENT "FocusedWindows:\n";
4353 for (auto& it : mFocusedWindowTokenByDisplay) {
4354 const int32_t displayId = it.first;
4355 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4356 if (windowHandle) {
4357 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4358 windowHandle->getName().c_str());
4359 } else {
4360 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4361 " has focused token without a window'\n",
4362 displayId);
4363 }
4364 }
4365 return dump;
4366}
4367
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004368void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004369 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4370 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4371 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004372 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Tiger Huang721e26f2018-07-24 22:26:19 +08004374 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4375 dump += StringPrintf(INDENT "FocusedApplications:\n");
4376 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4377 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004378 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004379 const std::chrono::duration timeout =
4380 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004382 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004383 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004386 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004388
Vishnu Nairad321cd2020-08-20 16:40:21 -07004389 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004391 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004392 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004393 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4394 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004395 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004396 state.displayId, toString(state.down), toString(state.split),
4397 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004398 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004399 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004400 for (size_t i = 0; i < state.windows.size(); i++) {
4401 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 dump += StringPrintf(INDENT4
4403 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4404 i, touchedWindow.windowHandle->getName().c_str(),
4405 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004406 }
4407 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004408 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004409 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004410 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004411 dump += INDENT3 "Portal windows:\n";
4412 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004413 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4415 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004416 }
4417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 }
4419 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004420 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422
Arthur Hungb92218b2018-08-14 12:00:21 +08004423 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004425 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004426 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004427 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004428 dump += INDENT2 "Windows:\n";
4429 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004430 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004431 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432
Arthur Hungb92218b2018-08-14 12:00:21 +08004433 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004434 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4435 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004436 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004438 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004439 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 i, windowInfo->name.c_str(), windowInfo->displayId,
4441 windowInfo->portalToDisplayId,
4442 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004443 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 toString(windowInfo->hasWallpaper),
4445 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004446 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004447 static_cast<int32_t>(windowInfo->type),
4448 windowInfo->frameLeft, windowInfo->frameTop,
4449 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004450 windowInfo->globalScaleFactor,
4451 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004452 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004453 dump += StringPrintf(", inputFeatures=%s",
4454 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004455 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4456 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004457 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004458 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004459 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004460 }
4461 } else {
4462 dump += INDENT2 "Windows: <none>\n";
4463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 }
4465 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004466 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 }
4468
Michael Wright3dd60e22019-03-27 22:06:44 +00004469 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004471 const std::vector<Monitor>& monitors = it.second;
4472 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4473 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 }
4475 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004476 const std::vector<Monitor>& monitors = it.second;
4477 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4478 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004481 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483
4484 nsecs_t currentTime = now();
4485
4486 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004487 if (!mRecentQueue.empty()) {
4488 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4489 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004490 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004491 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004492 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
4494 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004495 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 }
4497
4498 // Dump event currently being dispatched.
4499 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004500 dump += INDENT "PendingEvent:\n";
4501 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004502 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004503 dump += StringPrintf(", age=%" PRId64 "ms\n",
4504 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004506 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 }
4508
4509 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004510 if (!mInboundQueue.empty()) {
4511 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4512 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004513 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004514 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004515 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 }
4517 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004518 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
4520
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004521 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004522 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004523 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4524 const KeyReplacement& replacement = pair.first;
4525 int32_t newKeyCode = pair.second;
4526 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004528 }
4529 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004530 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004531 }
4532
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004533 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004534 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004535 for (const auto& pair : mConnectionsByFd) {
4536 const sp<Connection>& connection = pair.second;
4537 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004539 pair.first, connection->getInputChannelName().c_str(),
4540 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004541 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004543 if (!connection->outboundQueue.empty()) {
4544 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4545 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004546 dump += dumpQueue(connection->outboundQueue, currentTime);
4547
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004549 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 }
4551
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004552 if (!connection->waitQueue.empty()) {
4553 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4554 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004555 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004557 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
4560 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004561 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 }
4563
4564 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004565 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4566 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004568 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004571 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004572 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4573 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4574 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575}
4576
Michael Wright3dd60e22019-03-27 22:06:44 +00004577void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4578 const size_t numMonitors = monitors.size();
4579 for (size_t i = 0; i < numMonitors; i++) {
4580 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004581 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004582 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4583 dump += "\n";
4584 }
4585}
4586
Garfield Tan15601662020-09-22 15:32:38 -07004587base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4588 const std::string& name) {
4589#if DEBUG_CHANNEL_CREATION
4590 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591#endif
4592
Garfield Tan15601662020-09-22 15:32:38 -07004593 std::shared_ptr<InputChannel> serverChannel;
4594 std::unique_ptr<InputChannel> clientChannel;
4595 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4596
4597 if (result) {
4598 return base::Error(result) << "Failed to open input channel pair with name " << name;
4599 }
4600
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004602 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004603 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Garfield Tan15601662020-09-22 15:32:38 -07004605 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004606 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004607 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4610 } // release lock
4611
4612 // Wake the looper because some connections have changed.
4613 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004614 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615}
4616
Garfield Tan15601662020-09-22 15:32:38 -07004617base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4618 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4619 std::shared_ptr<InputChannel> serverChannel;
4620 std::unique_ptr<InputChannel> clientChannel;
4621 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4622 if (result) {
4623 return base::Error(result) << "Failed to open input channel pair with name " << name;
4624 }
4625
Michael Wright3dd60e22019-03-27 22:06:44 +00004626 { // acquire lock
4627 std::scoped_lock _l(mLock);
4628
4629 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004630 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4631 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004632 }
4633
Garfield Tan15601662020-09-22 15:32:38 -07004634 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004635
Garfield Tan15601662020-09-22 15:32:38 -07004636 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004637 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004638 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640 auto& monitorsByDisplay =
4641 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004642 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004643
4644 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004645 }
Garfield Tan15601662020-09-22 15:32:38 -07004646
Michael Wright3dd60e22019-03-27 22:06:44 +00004647 // Wake the looper because some connections have changed.
4648 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004649 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004650}
4651
Garfield Tan15601662020-09-22 15:32:38 -07004652status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004654 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655
Garfield Tan15601662020-09-22 15:32:38 -07004656 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 if (status) {
4658 return status;
4659 }
4660 } // release lock
4661
4662 // Wake the poll loop because removing the connection may have changed the current
4663 // synchronization state.
4664 mLooper->wake();
4665 return OK;
4666}
4667
Garfield Tan15601662020-09-22 15:32:38 -07004668status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4669 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004670 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004671 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004672 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 return BAD_VALUE;
4674 }
4675
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004676 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004677 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004678
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004680 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 }
4682
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004683 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
4685 nsecs_t currentTime = now();
4686 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4687
4688 connection->status = Connection::STATUS_ZOMBIE;
4689 return OK;
4690}
4691
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004692void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4693 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4694 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004695}
4696
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004697void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004698 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004699 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004701 std::vector<Monitor>& monitors = it->second;
4702 const size_t numMonitors = monitors.size();
4703 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004704 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004705 monitors.erase(monitors.begin() + i);
4706 break;
4707 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004708 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004709 if (monitors.empty()) {
4710 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004711 } else {
4712 ++it;
4713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 }
4715}
4716
Michael Wright3dd60e22019-03-27 22:06:44 +00004717status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4718 { // acquire lock
4719 std::scoped_lock _l(mLock);
4720 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4721
4722 if (!foundDisplayId) {
4723 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4724 return BAD_VALUE;
4725 }
4726 int32_t displayId = foundDisplayId.value();
4727
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004728 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4729 mTouchStatesByDisplay.find(displayId);
4730 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004731 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4732 return BAD_VALUE;
4733 }
4734
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004735 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004736 std::optional<int32_t> foundDeviceId;
4737 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004738 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004739 foundDeviceId = state.deviceId;
4740 }
4741 }
4742 if (!foundDeviceId || !state.down) {
4743 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004745 return BAD_VALUE;
4746 }
4747 int32_t deviceId = foundDeviceId.value();
4748
4749 // Send cancel events to all the input channels we're stealing from.
4750 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004752 options.deviceId = deviceId;
4753 options.displayId = displayId;
4754 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004755 std::shared_ptr<InputChannel> channel =
4756 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004757 if (channel != nullptr) {
4758 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4759 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004760 }
4761 // Then clear the current touch state so we stop dispatching to them as well.
4762 state.filterNonMonitors();
4763 }
4764 return OK;
4765}
4766
Michael Wright3dd60e22019-03-27 22:06:44 +00004767std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4768 const sp<IBinder>& token) {
4769 for (const auto& it : mGestureMonitorsByDisplay) {
4770 const std::vector<Monitor>& monitors = it.second;
4771 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004772 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004773 return it.first;
4774 }
4775 }
4776 }
4777 return std::nullopt;
4778}
4779
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004780sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004781 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004782 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004783 }
4784
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004785 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004786 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004787 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004788 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 }
4790 }
Robert Carr4e670e52018-08-15 13:26:12 -07004791
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004792 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793}
4794
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004795void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004797 removeByValue(mConnectionsByFd, connection);
4798}
4799
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4801 const sp<Connection>& connection, uint32_t seq,
4802 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004803 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4804 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 commandEntry->connection = connection;
4806 commandEntry->eventTime = currentTime;
4807 commandEntry->seq = seq;
4808 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004809 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810}
4811
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4813 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004815 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004817 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4818 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004820 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821}
4822
Vishnu Nairad321cd2020-08-20 16:40:21 -07004823void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4824 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004825 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4826 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004827 commandEntry->oldToken = oldToken;
4828 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004829 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004830}
4831
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004832void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4834 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004835 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004837 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 return;
4839 }
4840 /**
4841 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4842 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4843 * has changed. This could cause newer entries to time out before the already dispatched
4844 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4845 * processes the events linearly. So providing information about the oldest entry seems to be
4846 * most useful.
4847 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004848 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4850 std::string reason =
4851 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004852 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853 ns2ms(currentWait),
4854 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004856 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 reason);
4858
4859 std::unique_ptr<CommandEntry> commandEntry =
4860 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4861 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004862 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 commandEntry->reason = std::move(reason);
4864 postCommandLocked(std::move(commandEntry));
4865}
4866
Chris Yea209fde2020-07-22 13:54:51 -07004867void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4869 application->getName().c_str());
4870
4871 updateLastAnrStateLocked(application, reason);
4872
4873 std::unique_ptr<CommandEntry> commandEntry =
4874 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4875 commandEntry->inputApplicationHandle = application;
4876 commandEntry->inputChannel = nullptr;
4877 commandEntry->reason = std::move(reason);
4878 postCommandLocked(std::move(commandEntry));
4879}
4880
4881void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4882 const std::string& reason) {
4883 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4884 updateLastAnrStateLocked(windowLabel, reason);
4885}
4886
Chris Yea209fde2020-07-22 13:54:51 -07004887void InputDispatcher::updateLastAnrStateLocked(
4888 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4890 updateLastAnrStateLocked(windowLabel, reason);
4891}
4892
4893void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4894 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004896 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 struct tm tm;
4898 localtime_r(&t, &tm);
4899 char timestr[64];
4900 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004901 mLastAnrState.clear();
4902 mLastAnrState += INDENT "ANR:\n";
4903 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4905 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004906 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907}
4908
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004909void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 mLock.unlock();
4911
4912 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4913
4914 mLock.lock();
4915}
4916
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004917void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 sp<Connection> connection = commandEntry->connection;
4919
4920 if (connection->status != Connection::STATUS_ZOMBIE) {
4921 mLock.unlock();
4922
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004923 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924
4925 mLock.lock();
4926 }
4927}
4928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004929void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004930 sp<IBinder> oldToken = commandEntry->oldToken;
4931 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004932 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004933 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004934 mLock.lock();
4935}
4936
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004937void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004938 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004939 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 mLock.unlock();
4941
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004942 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004943 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
4945 mLock.lock();
4946
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004947 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4949 } else {
4950 // stop waking up for events in this connection, it is already not responding
4951 sp<Connection> connection = getConnectionLocked(token);
4952 if (connection == nullptr) {
4953 return;
4954 }
4955 cancelEventsForAnrLocked(connection);
4956 }
4957}
4958
Chris Yea209fde2020-07-22 13:54:51 -07004959void InputDispatcher::extendAnrTimeoutsLocked(
4960 const std::shared_ptr<InputApplicationHandle>& application,
4961 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004962 if (connectionToken == nullptr && application != nullptr) {
4963 // The ANR happened because there's no focused window
4964 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
4965 mAwaitedFocusedApplication = application;
4966 }
4967
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004968 sp<Connection> connection = getConnectionLocked(connectionToken);
4969 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004970 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971 return;
4972 }
4973
4974 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004975 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976
4977 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004978 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004979 for (DispatchEntry* entry : connection->waitQueue) {
4980 if (newTimeout >= entry->timeoutTime) {
4981 // Already removed old entries when connection was marked unresponsive
4982 entry->timeoutTime = newTimeout;
4983 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4984 }
4985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986}
4987
4988void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4989 CommandEntry* commandEntry) {
4990 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004991 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992
4993 mLock.unlock();
4994
Michael Wright2b3c3302018-03-02 17:19:13 +00004995 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004997 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004998 : nullptr;
4999 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005000 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5001 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005002 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
5005 mLock.lock();
5006
5007 if (delay < 0) {
5008 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5009 } else if (!delay) {
5010 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5011 } else {
5012 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5013 entry->interceptKeyWakeupTime = now() + delay;
5014 }
5015 entry->release();
5016}
5017
chaviwfd6d3512019-03-25 13:23:49 -07005018void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5019 mLock.unlock();
5020 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5021 mLock.lock();
5022}
5023
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024/**
5025 * Connection is responsive if it has no events in the waitQueue that are older than the
5026 * current time.
5027 */
5028static bool isConnectionResponsive(const Connection& connection) {
5029 const nsecs_t currentTime = now();
5030 for (const DispatchEntry* entry : connection.waitQueue) {
5031 if (entry->timeoutTime < currentTime) {
5032 return false;
5033 }
5034 }
5035 return true;
5036}
5037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005040 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005042 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043
5044 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005045 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005046 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005047 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005049 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005050 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005051 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005052 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5053 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005054 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005055 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005056
5057 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005058 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005059 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5060 restartEvent =
5061 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005062 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005063 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5064 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5065 handled);
5066 } else {
5067 restartEvent = false;
5068 }
5069
5070 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005071 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005072 // contents of the wait queue to have been drained, so we need to double-check
5073 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005074 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5075 if (dispatchEntryIt != connection->waitQueue.end()) {
5076 dispatchEntry = *dispatchEntryIt;
5077 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005078 mAnrTracker.erase(dispatchEntry->timeoutTime,
5079 connection->inputChannel->getConnectionToken());
5080 if (!connection->responsive) {
5081 connection->responsive = isConnectionResponsive(*connection);
5082 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005083 traceWaitQueueLength(connection);
5084 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005085 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005086 traceOutboundQueueLength(connection);
5087 } else {
5088 releaseDispatchEntry(dispatchEntry);
5089 }
5090 }
5091
5092 // Start the next dispatch cycle for this connection.
5093 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094}
5095
5096bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005097 DispatchEntry* dispatchEntry,
5098 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005099 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005100 if (!handled) {
5101 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005102 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005103 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005104 return false;
5105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005107 // Get the fallback key state.
5108 // Clear it out after dispatching the UP.
5109 int32_t originalKeyCode = keyEntry->keyCode;
5110 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5111 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5112 connection->inputState.removeFallbackKey(originalKeyCode);
5113 }
5114
5115 if (handled || !dispatchEntry->hasForegroundTarget()) {
5116 // If the application handles the original key for which we previously
5117 // generated a fallback or if the window is not a foreground window,
5118 // then cancel the associated fallback key, if any.
5119 if (fallbackKeyCode != -1) {
5120 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005122 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005123 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5124 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5125 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005127 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005128 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129
5130 mLock.unlock();
5131
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005132 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005133 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134
5135 mLock.lock();
5136
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005137 // Cancel the fallback key.
5138 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005140 "application handled the original non-fallback key "
5141 "or is no longer a foreground target, "
5142 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 options.keyCode = fallbackKeyCode;
5144 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005146 connection->inputState.removeFallbackKey(originalKeyCode);
5147 }
5148 } else {
5149 // If the application did not handle a non-fallback key, first check
5150 // that we are in a good state to perform unhandled key event processing
5151 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005152 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005153 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005155 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 "since this is not an initial down. "
5157 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5158 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005160 return false;
5161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005163 // Dispatch the unhandled key to the policy.
5164#if DEBUG_OUTBOUND_EVENT_DETAILS
5165 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5167 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005168#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005169 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005170
5171 mLock.unlock();
5172
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005173 bool fallback =
5174 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5175 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005176
5177 mLock.lock();
5178
5179 if (connection->status != Connection::STATUS_NORMAL) {
5180 connection->inputState.removeFallbackKey(originalKeyCode);
5181 return false;
5182 }
5183
5184 // Latch the fallback keycode for this key on an initial down.
5185 // The fallback keycode cannot change at any other point in the lifecycle.
5186 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005188 fallbackKeyCode = event.getKeyCode();
5189 } else {
5190 fallbackKeyCode = AKEYCODE_UNKNOWN;
5191 }
5192 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5193 }
5194
5195 ALOG_ASSERT(fallbackKeyCode != -1);
5196
5197 // Cancel the fallback key if the policy decides not to send it anymore.
5198 // We will continue to dispatch the key to the policy but we will no
5199 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005200 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5201 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005202#if DEBUG_OUTBOUND_EVENT_DETAILS
5203 if (fallback) {
5204 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005205 "as a fallback for %d, but on the DOWN it had requested "
5206 "to send %d instead. Fallback canceled.",
5207 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005208 } else {
5209 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005210 "but on the DOWN it had requested to send %d. "
5211 "Fallback canceled.",
5212 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005213 }
5214#endif
5215
5216 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5217 "canceling fallback, policy no longer desires it");
5218 options.keyCode = fallbackKeyCode;
5219 synthesizeCancelationEventsForConnectionLocked(connection, options);
5220
5221 fallback = false;
5222 fallbackKeyCode = AKEYCODE_UNKNOWN;
5223 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005225 }
5226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227
5228#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005229 {
5230 std::string msg;
5231 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5232 connection->inputState.getFallbackKeys();
5233 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005234 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005236 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005237 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005238 }
5239#endif
5240
5241 if (fallback) {
5242 // Restart the dispatch cycle using the fallback key.
5243 keyEntry->eventTime = event.getEventTime();
5244 keyEntry->deviceId = event.getDeviceId();
5245 keyEntry->source = event.getSource();
5246 keyEntry->displayId = event.getDisplayId();
5247 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5248 keyEntry->keyCode = fallbackKeyCode;
5249 keyEntry->scanCode = event.getScanCode();
5250 keyEntry->metaState = event.getMetaState();
5251 keyEntry->repeatCount = event.getRepeatCount();
5252 keyEntry->downTime = event.getDownTime();
5253 keyEntry->syntheticRepeat = false;
5254
5255#if DEBUG_OUTBOUND_EVENT_DETAILS
5256 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5258 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005259#endif
5260 return true; // restart the event
5261 } else {
5262#if DEBUG_OUTBOUND_EVENT_DETAILS
5263 ALOGD("Unhandled key event: No fallback key.");
5264#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005265
5266 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005267 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 }
5269 }
5270 return false;
5271}
5272
5273bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005274 DispatchEntry* dispatchEntry,
5275 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 return false;
5277}
5278
5279void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5280 mLock.unlock();
5281
5282 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5283
5284 mLock.lock();
5285}
5286
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005287KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5288 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005289 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005290 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5291 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005292 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293}
5294
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005295void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5296 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 // TODO Write some statistics about how long we spend waiting.
5298}
5299
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005300/**
5301 * Report the touch event latency to the statsd server.
5302 * Input events are reported for statistics if:
5303 * - This is a touchscreen event
5304 * - InputFilter is not enabled
5305 * - Event is not injected or synthesized
5306 *
5307 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5308 * from getting aggregated with the "old" data.
5309 */
5310void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5311 REQUIRES(mLock) {
5312 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5313 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5314 if (!reportForStatistics) {
5315 return;
5316 }
5317
5318 if (mTouchStatistics.shouldReport()) {
5319 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5320 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5321 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5322 mTouchStatistics.reset();
5323 }
5324 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5325 mTouchStatistics.addValue(latencyMicros);
5326}
5327
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328void InputDispatcher::traceInboundQueueLengthLocked() {
5329 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005330 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 }
5332}
5333
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005334void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 if (ATRACE_ENABLED()) {
5336 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005337 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005338 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 }
5340}
5341
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005342void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 if (ATRACE_ENABLED()) {
5344 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005345 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005346 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 }
5348}
5349
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005350void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005351 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005353 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 dumpDispatchStateLocked(dump);
5355
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005356 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005357 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005358 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
5360}
5361
5362void InputDispatcher::monitor() {
5363 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005364 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005366 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367}
5368
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005369/**
5370 * Wake up the dispatcher and wait until it processes all events and commands.
5371 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5372 * this method can be safely called from any thread, as long as you've ensured that
5373 * the work you are interested in completing has already been queued.
5374 */
5375bool InputDispatcher::waitForIdle() {
5376 /**
5377 * Timeout should represent the longest possible time that a device might spend processing
5378 * events and commands.
5379 */
5380 constexpr std::chrono::duration TIMEOUT = 100ms;
5381 std::unique_lock lock(mLock);
5382 mLooper->wake();
5383 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5384 return result == std::cv_status::no_timeout;
5385}
5386
Vishnu Naire798b472020-07-23 13:52:21 -07005387/**
5388 * Sets focus to the window identified by the token. This must be called
5389 * after updating any input window handles.
5390 *
5391 * Params:
5392 * request.token - input channel token used to identify the window that should gain focus.
5393 * request.focusedToken - the token that the caller expects currently to be focused. If the
5394 * specified token does not match the currently focused window, this request will be dropped.
5395 * If the specified focused token matches the currently focused window, the call will succeed.
5396 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5397 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5398 * when requesting the focus change. This determines which request gets
5399 * precedence if there is a focus change request from another source such as pointer down.
5400 */
Vishnu Nair958da932020-08-21 17:12:37 -07005401void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5402 { // acquire lock
5403 std::scoped_lock _l(mLock);
5404
5405 const int32_t displayId = request.displayId;
5406 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5407 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5408 ALOGD_IF(DEBUG_FOCUS,
5409 "setFocusedWindow on display %" PRId32
5410 " ignored, reason: focusedToken is not focused",
5411 displayId);
5412 return;
5413 }
5414
5415 mPendingFocusRequests.erase(displayId);
5416 FocusResult result = handleFocusRequestLocked(request);
5417 if (result == FocusResult::NOT_VISIBLE) {
5418 // The requested window is not currently visible. Wait for the window to become visible
5419 // and then provide it focus. This is to handle situations where a user action triggers
5420 // a new window to appear. We want to be able to queue any key events after the user
5421 // action and deliver it to the newly focused window. In order for this to happen, we
5422 // take focus from the currently focused window so key events can be queued.
5423 ALOGD_IF(DEBUG_FOCUS,
5424 "setFocusedWindow on display %" PRId32
5425 " pending, reason: window is not visible",
5426 displayId);
5427 mPendingFocusRequests[displayId] = request;
5428 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5429 "setFocusedWindow_AwaitingWindowVisibility");
5430 } else if (result != FocusResult::OK) {
5431 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5432 typeToString(result));
5433 }
5434 } // release lock
5435 // Wake up poll loop since it may need to make new input dispatching choices.
5436 mLooper->wake();
5437}
5438
5439InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5440 const FocusRequest& request) {
5441 const int32_t displayId = request.displayId;
5442 const sp<IBinder> newFocusedToken = request.token;
5443 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5444
5445 if (oldFocusedToken == request.token) {
5446 ALOGD_IF(DEBUG_FOCUS,
5447 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5448 displayId);
5449 return FocusResult::OK;
5450 }
5451
5452 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5453 if (result != FocusResult::OK) {
5454 return result;
5455 }
5456
5457 std::string_view reason =
5458 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5459 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5460 return FocusResult::OK;
5461}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005462
Vishnu Nairad321cd2020-08-20 16:40:21 -07005463void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5464 const sp<IBinder>& newFocusedToken, int32_t displayId,
5465 std::string_view reason) {
5466 if (oldFocusedToken) {
5467 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005468 if (focusedInputChannel) {
5469 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5470 "focus left window");
5471 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005472 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005473 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005474 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005475 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005476 if (newFocusedToken) {
5477 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5478 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005479 }
5480
5481 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005482 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005483 }
5484}
Vishnu Nair958da932020-08-21 17:12:37 -07005485
5486/**
5487 * Checks if the window token can be focused on a display. The token can be focused if there is
5488 * at least one window handle that is visible with the same token and all window handles with the
5489 * same token are focusable.
5490 *
5491 * In the case of mirroring, two windows may share the same window token and their visibility
5492 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5493 * we expect the focusability of the windows to match since its hard to reason why one window can
5494 * receive focus events and the other cannot when both are backed by the same input channel.
5495 */
5496InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5497 int32_t displayId) const {
5498 bool allWindowsAreFocusable = true;
5499 bool visibleWindowFound = false;
5500 bool windowFound = false;
5501 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5502 if (window->getToken() != token) {
5503 continue;
5504 }
5505 windowFound = true;
5506 if (window->getInfo()->visible) {
5507 // Check if at least a single window is visible.
5508 visibleWindowFound = true;
5509 }
5510 if (!window->getInfo()->focusable) {
5511 // Check if all windows with the window token are focusable.
5512 allWindowsAreFocusable = false;
5513 break;
5514 }
5515 }
5516
5517 if (!windowFound) {
5518 return FocusResult::NO_WINDOW;
5519 }
5520 if (!allWindowsAreFocusable) {
5521 return FocusResult::NOT_FOCUSABLE;
5522 }
5523 if (!visibleWindowFound) {
5524 return FocusResult::NOT_VISIBLE;
5525 }
5526
5527 return FocusResult::OK;
5528}
Garfield Tane84e6f92019-08-29 17:28:41 -07005529} // namespace android::inputdispatcher