blob: 464236dfb3b3d29a4d406eabf96ea9471d6a88b2 [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
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070050#include <InputFlingerProperties.sysprop.h>
Michael Wright2b3c3302018-03-02 17:19:13 +000051#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050054#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070055#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100056#include <binder/IServiceManager.h>
57#include <com/android/internal/compat/IPlatformCompatNative.h>
chaviw15fab6f2021-06-07 14:15:52 -050058#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080059#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000061#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070062#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010063#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000083using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050085using android::gui::FocusRequest;
86using android::gui::TouchOcclusionMode;
87using android::gui::WindowInfo;
88using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080089using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100090using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080091using android::os::InputEventInjectionResult;
92using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100093using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080094
Garfield Tane84e6f92019-08-29 17:28:41 -070095namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Prabir Pradhan93a0f912021-04-21 13:47:42 -070097// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
98// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
99static bool isPerWindowInputRotationEnabled() {
100 static const bool PER_WINDOW_INPUT_ROTATION =
Vadim Tryshev7719c7d2021-08-27 17:28:43 +0000101 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700102
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700103 return PER_WINDOW_INPUT_ROTATION;
104}
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106// Default input dispatching timeout if there is no focused application or paused window
107// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800108const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
109 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
110 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111
112// Amount of time to allow for all pending events to be processed when an app switch
113// key is on the way. This is used to preempt input dispatch and drop input events
114// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000115constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116
117// Amount of time to allow for an event to be dispatched (measured since its eventTime)
118// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
Michael Wrightd02c5b62014-02-10 15:10:22 -0800121// 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 +0000122constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
123
124// Log a warning when an interception call takes longer than this to process.
125constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700127// Additional key latency in case a connection is still processing some motion events.
128// This will help with the case when a user touched a button that opens a new window,
129// and gives us the chance to dispatch the key to this new window.
130constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
131
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000133constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
134
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000135// Event log tags. See EventLogTags.logtags for reference
136constexpr int LOGTAG_INPUT_INTERACTION = 62000;
137constexpr int LOGTAG_INPUT_FOCUS = 62001;
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139static inline nsecs_t now() {
140 return systemTime(SYSTEM_TIME_MONOTONIC);
141}
142
143static inline const char* toString(bool value) {
144 return value ? "true" : "false";
145}
146
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000147static inline const std::string toString(sp<IBinder> binder) {
148 if (binder == nullptr) {
149 return "<null>";
150 }
151 return StringPrintf("%p", binder.get());
152}
153
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
156 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157}
158
159static bool isValidKeyAction(int32_t action) {
160 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 case AKEY_EVENT_ACTION_DOWN:
162 case AKEY_EVENT_ACTION_UP:
163 return true;
164 default:
165 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 }
167}
168
169static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 ALOGE("Key event has invalid action code 0x%x", action);
172 return false;
173 }
174 return true;
175}
176
Michael Wright7b159c92015-05-14 14:48:03 +0100177static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700179 case AMOTION_EVENT_ACTION_DOWN:
180 case AMOTION_EVENT_ACTION_UP:
181 case AMOTION_EVENT_ACTION_CANCEL:
182 case AMOTION_EVENT_ACTION_MOVE:
183 case AMOTION_EVENT_ACTION_OUTSIDE:
184 case AMOTION_EVENT_ACTION_HOVER_ENTER:
185 case AMOTION_EVENT_ACTION_HOVER_MOVE:
186 case AMOTION_EVENT_ACTION_HOVER_EXIT:
187 case AMOTION_EVENT_ACTION_SCROLL:
188 return true;
189 case AMOTION_EVENT_ACTION_POINTER_DOWN:
190 case AMOTION_EVENT_ACTION_POINTER_UP: {
191 int32_t index = getMotionEventActionPointerIndex(action);
192 return index >= 0 && index < pointerCount;
193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
196 return actionButton != 0;
197 default:
198 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 }
200}
201
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500202static int64_t millis(std::chrono::nanoseconds t) {
203 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
204}
205
Michael Wright7b159c92015-05-14 14:48:03 +0100206static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700207 const PointerProperties* pointerProperties) {
208 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 ALOGE("Motion event has invalid action code 0x%x", action);
210 return false;
211 }
212 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000213 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 return false;
216 }
217 BitSet32 pointerIdBits;
218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700221 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
222 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 return false;
224 }
225 if (pointerIdBits.hasBit(id)) {
226 ALOGE("Motion event has duplicate pointer id %d", id);
227 return false;
228 }
229 pointerIdBits.markBit(id);
230 }
231 return true;
232}
233
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000234static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000236 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 }
238
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000239 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 bool first = true;
241 Region::const_iterator cur = region.begin();
242 Region::const_iterator const tail = region.end();
243 while (cur != tail) {
244 if (first) {
245 first = false;
246 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800247 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800249 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 cur++;
251 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000252 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253}
254
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500255static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
256 constexpr size_t maxEntries = 50; // max events to print
257 constexpr size_t skipBegin = maxEntries / 2;
258 const size_t skipEnd = queue.size() - maxEntries / 2;
259 // skip from maxEntries / 2 ... size() - maxEntries/2
260 // only print from 0 .. skipBegin and then from skipEnd .. size()
261
262 std::string dump;
263 for (size_t i = 0; i < queue.size(); i++) {
264 const DispatchEntry& entry = *queue[i];
265 if (i >= skipBegin && i < skipEnd) {
266 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
267 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
268 continue;
269 }
270 dump.append(INDENT4);
271 dump += entry.eventEntry->getDescription();
272 dump += StringPrintf(", seq=%" PRIu32
273 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
274 entry.seq, entry.targetFlags, entry.resolvedAction,
275 ns2ms(currentTime - entry.eventEntry->eventTime));
276 if (entry.deliveryTime != 0) {
277 // This entry was delivered, so add information on how long we've been waiting
278 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
279 }
280 dump.append("\n");
281 }
282 return dump;
283}
284
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700285/**
286 * Find the entry in std::unordered_map by key, and return it.
287 * If the entry is not found, return a default constructed entry.
288 *
289 * Useful when the entries are vectors, since an empty vector will be returned
290 * if the entry is not found.
291 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
292 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700293template <typename K, typename V>
294static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700295 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700296 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800297}
298
chaviw3277faf2021-05-19 16:45:23 -0500299static bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700300 if (first == second) {
301 return true;
302 }
303
304 if (first == nullptr || second == nullptr) {
305 return false;
306 }
307
308 return first->getToken() == second->getToken();
309}
310
chaviw3277faf2021-05-19 16:45:23 -0500311static bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000312 if (first == nullptr || second == nullptr) {
313 return false;
314 }
315 return first->applicationInfo.token != nullptr &&
316 first->applicationInfo.token == second->applicationInfo.token;
317}
318
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800319static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
320 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
321}
322
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700324 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000325 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900326 if (eventEntry->type == EventEntry::Type::MOTION) {
327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700328 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
329 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900330 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700331 // Use identity transform for joystick and position-based (touchpad) events because they
332 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900333 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700334 1.0f /*globalScaleFactor*/,
Evan Rosky09576692021-07-01 12:22:09 -0700335 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700336 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900337 }
338 }
339
chaviw1ff3d1e2020-07-01 15:53:47 -0700340 if (inputTarget.useDefaultPointerTransform()) {
341 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700342 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700343 inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700344 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700345 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000346 }
347
348 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
349 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
350
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700351 std::vector<PointerCoords> pointerCoords;
352 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353
354 // Use the first pointer information to normalize all other pointers. This could be any pointer
355 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 // uses the transform for the normalized pointer.
357 const ui::Transform& firstPointerTransform =
358 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
359 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360
361 // Iterate through all pointers in the event to normalize against the first.
362 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
363 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
364 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // First, apply the current pointer's transform to update the coordinates into
369 // window space.
370 pointerCoords[pointerIndex].transform(currTransform);
371 // Next, apply the inverse transform of the normalized coordinates so the
372 // current coordinates are transformed into the normalized coordinate space.
373 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374 }
375
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700376 std::unique_ptr<MotionEntry> combinedMotionEntry =
377 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
378 motionEntry.deviceId, motionEntry.source,
379 motionEntry.displayId, motionEntry.policyFlags,
380 motionEntry.action, motionEntry.actionButton,
381 motionEntry.flags, motionEntry.metaState,
382 motionEntry.buttonState, motionEntry.classification,
383 motionEntry.edgeFlags, motionEntry.xPrecision,
384 motionEntry.yPrecision, motionEntry.xCursorPosition,
385 motionEntry.yCursorPosition, motionEntry.downTime,
386 motionEntry.pointerCount, motionEntry.pointerProperties,
387 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388
389 if (motionEntry.injectionState) {
390 combinedMotionEntry->injectionState = motionEntry.injectionState;
391 combinedMotionEntry->injectionState->refCount += 1;
392 }
393
394 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700395 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700396 firstPointerTransform, inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700397 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700398 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399 return dispatchEntry;
400}
401
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700402static void addGestureMonitors(const std::vector<Monitor>& monitors,
403 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
404 float yOffset = 0) {
405 if (monitors.empty()) {
406 return;
407 }
408 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
409 for (const Monitor& monitor : monitors) {
410 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
411 }
412}
413
Garfield Tan15601662020-09-22 15:32:38 -0700414static status_t openInputChannelPair(const std::string& name,
415 std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422}
423
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424template <typename T>
425static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433}
434
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000435static sp<IPlatformCompatNative> getCompatService() {
436 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
437 if (service == nullptr) {
438 ALOGE("Failed to link to compat service");
439 return nullptr;
440 }
441 return interface_cast<IPlatformCompatNative>(service);
442}
443
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000444static KeyEvent createKeyEvent(const KeyEntry& entry) {
445 KeyEvent event;
446 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
447 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
448 entry.repeatCount, entry.downTime, entry.eventTime);
449 return event;
450}
451
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000452static std::optional<int32_t> findMonitorPidByToken(
453 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
454 const sp<IBinder>& token) {
455 for (const auto& it : monitorsByDisplay) {
456 const std::vector<Monitor>& monitors = it.second;
457 for (const Monitor& monitor : monitors) {
458 if (monitor.inputChannel->getConnectionToken() == token) {
459 return monitor.pid;
460 }
461 }
462 }
463 return std::nullopt;
464}
465
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000466static bool shouldReportMetricsForConnection(const Connection& connection) {
467 // Do not keep track of gesture monitors. They receive every event and would disproportionately
468 // affect the statistics.
469 if (connection.monitor) {
470 return false;
471 }
472 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
473 if (!connection.responsive) {
474 return false;
475 }
476 return true;
477}
478
479static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
480 const Connection& connection) {
481 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
482 const int32_t& inputEventId = eventEntry.id;
483 if (inputEventId != dispatchEntry.resolvedEventId) {
484 // Event was transmuted
485 return false;
486 }
487 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
488 return false;
489 }
490 // Only track latency for events that originated from hardware
491 if (eventEntry.isSynthesized()) {
492 return false;
493 }
494 const EventEntry::Type& inputEventEntryType = eventEntry.type;
495 if (inputEventEntryType == EventEntry::Type::KEY) {
496 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
497 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
498 return false;
499 }
500 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
501 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
502 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
503 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
504 return false;
505 }
506 } else {
507 // Not a key or a motion
508 return false;
509 }
510 if (!shouldReportMetricsForConnection(connection)) {
511 return false;
512 }
513 return true;
514}
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516// --- InputDispatcher ---
517
Garfield Tan00f511d2019-06-12 16:55:40 -0700518InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
519 : mPolicy(policy),
520 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700521 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800522 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700523 mAppSwitchSawKeyDown(false),
524 mAppSwitchDueTime(LONG_LONG_MAX),
525 mNextUnblockedEvent(nullptr),
526 mDispatchEnabled(false),
527 mDispatchFrozen(false),
528 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800529 // mInTouchMode will be initialized by the WindowManager to the default device config.
530 // To avoid leaking stack in case that call never comes, and for tests,
531 // initialize it here anyways.
532 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100533 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000534 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800535 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000536 mLatencyAggregator(),
537 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000538 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800540 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541
Yi Kong9b14ac62018-07-17 13:48:38 -0700542 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
544 policy->getDispatcherConfiguration(&mConfig);
545}
546
547InputDispatcher::~InputDispatcher() {
548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800549 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550
551 resetKeyRepeatLocked();
552 releasePendingEventLocked();
553 drainInboundQueueLocked();
554 }
555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000556 while (!mConnectionsByToken.empty()) {
557 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700558 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560}
561
chaviw15fab6f2021-06-07 14:15:52 -0500562void InputDispatcher::onFirstRef() {
563 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
564}
565
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700566status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700567 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700568 return ALREADY_EXISTS;
569 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700570 mThread = std::make_unique<InputThread>(
571 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
572 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700573}
574
575status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700576 if (mThread && mThread->isCallingThread()) {
577 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700578 return INVALID_OPERATION;
579 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700580 mThread.reset();
581 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700582}
583
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584void InputDispatcher::dispatchOnce() {
585 nsecs_t nextWakeupTime = LONG_LONG_MAX;
586 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800587 std::scoped_lock _l(mLock);
588 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589
590 // Run a dispatch loop if there are no pending commands.
591 // The dispatch loop might enqueue commands to run afterwards.
592 if (!haveCommandsLocked()) {
593 dispatchOnceInnerLocked(&nextWakeupTime);
594 }
595
596 // Run all pending commands if there are any.
597 // If any commands were run then force the next poll to wake up immediately.
598 if (runCommandsLockedInterruptible()) {
599 nextWakeupTime = LONG_LONG_MIN;
600 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800601
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700602 // If we are still waiting for ack on some events,
603 // we might have to wake up earlier to check if an app is anr'ing.
604 const nsecs_t nextAnrCheck = processAnrsLocked();
605 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
606
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800607 // We are about to enter an infinitely long sleep, because we have no commands or
608 // pending or queued events
609 if (nextWakeupTime == LONG_LONG_MAX) {
610 mDispatcherEnteredIdle.notify_all();
611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 } // release lock
613
614 // Wait for callback or timeout or wake. (make sure we round up, not down)
615 nsecs_t currentTime = now();
616 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
617 mLooper->pollOnce(timeoutMillis);
618}
619
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500621 * Raise ANR if there is no focused window.
622 * Before the ANR is raised, do a final state check:
623 * 1. The currently focused application must be the same one we are waiting for.
624 * 2. Ensure we still don't have a focused window.
625 */
626void InputDispatcher::processNoFocusedWindowAnrLocked() {
627 // Check if the application that we are waiting for is still focused.
628 std::shared_ptr<InputApplicationHandle> focusedApplication =
629 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
630 if (focusedApplication == nullptr ||
631 focusedApplication->getApplicationToken() !=
632 mAwaitedFocusedApplication->getApplicationToken()) {
633 // Unexpected because we should have reset the ANR timer when focused application changed
634 ALOGE("Waited for a focused window, but focused application has already changed to %s",
635 focusedApplication->getName().c_str());
636 return; // The focused application has changed.
637 }
638
chaviw3277faf2021-05-19 16:45:23 -0500639 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500640 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
641 if (focusedWindowHandle != nullptr) {
642 return; // We now have a focused window. No need for ANR.
643 }
644 onAnrLocked(mAwaitedFocusedApplication);
645}
646
647/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648 * Check if any of the connections' wait queues have events that are too old.
649 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
650 * Return the time at which we should wake up next.
651 */
652nsecs_t InputDispatcher::processAnrsLocked() {
653 const nsecs_t currentTime = now();
654 nsecs_t nextAnrCheck = LONG_LONG_MAX;
655 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
656 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
657 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500658 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700659 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500660 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661 return LONG_LONG_MIN;
662 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500663 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700664 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
665 }
666 }
667
668 // Check if any connection ANRs are due
669 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
670 if (currentTime < nextAnrCheck) { // most likely scenario
671 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
672 }
673
674 // If we reached here, we have an unresponsive connection.
675 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
676 if (connection == nullptr) {
677 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
678 return nextAnrCheck;
679 }
680 connection->responsive = false;
681 // Stop waking up for this unresponsive connection
682 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000683 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700684 return LONG_LONG_MIN;
685}
686
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500687std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw3277faf2021-05-19 16:45:23 -0500688 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500690 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500692 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700693}
694
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
696 nsecs_t currentTime = now();
697
Jeff Browndc5992e2014-04-11 01:27:26 -0700698 // Reset the key repeat timer whenever normal dispatch is suspended while the
699 // device is in a non-interactive state. This is to ensure that we abort a key
700 // repeat if the device is just coming out of sleep.
701 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 resetKeyRepeatLocked();
703 }
704
705 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
706 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100707 if (DEBUG_FOCUS) {
708 ALOGD("Dispatch frozen. Waiting some more.");
709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 return;
711 }
712
713 // Optimize latency of app switches.
714 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
715 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
716 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
717 if (mAppSwitchDueTime < *nextWakeupTime) {
718 *nextWakeupTime = mAppSwitchDueTime;
719 }
720
721 // Ready to start a new event.
722 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700723 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700724 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 if (isAppSwitchDue) {
726 // The inbound queue is empty so the app switch key we were waiting
727 // for will never arrive. Stop waiting for it.
728 resetPendingAppSwitchLocked(false);
729 isAppSwitchDue = false;
730 }
731
732 // Synthesize a key repeat if appropriate.
733 if (mKeyRepeatState.lastKeyEntry) {
734 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
735 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
736 } else {
737 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
738 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
739 }
740 }
741 }
742
743 // Nothing to do if there is no pending event.
744 if (!mPendingEvent) {
745 return;
746 }
747 } else {
748 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700749 mPendingEvent = mInboundQueue.front();
750 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 traceInboundQueueLengthLocked();
752 }
753
754 // Poke user activity for this event.
755 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700756 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 }
759
760 // Now we have an event to dispatch.
761 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700762 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700764 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700766 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700768 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
770
771 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700772 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 }
774
775 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700776 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700777 const ConfigurationChangedEntry& typedEntry =
778 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 break;
782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700784 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700785 const DeviceResetEntry& typedEntry =
786 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 break;
790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100792 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700793 std::shared_ptr<FocusEntry> typedEntry =
794 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100795 dispatchFocusLocked(currentTime, typedEntry);
796 done = true;
797 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
798 break;
799 }
800
Prabir Pradhan99987712020-11-10 18:43:05 -0800801 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
802 const auto typedEntry =
803 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
804 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
805 done = true;
806 break;
807 }
808
arthurhungb89ccb02020-12-30 16:19:01 +0800809 case EventEntry::Type::DRAG: {
810 std::shared_ptr<DragEntry> typedEntry =
811 std::static_pointer_cast<DragEntry>(mPendingEvent);
812 dispatchDragLocked(currentTime, typedEntry);
813 done = true;
814 break;
815 }
816
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700817 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700818 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 resetPendingAppSwitchLocked(true);
822 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 } else if (dropReason == DropReason::NOT_DROPPED) {
824 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
826 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700827 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700830 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
831 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700833 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 break;
835 }
836
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700837 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700838 std::shared_ptr<MotionEntry> motionEntry =
839 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700840 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
841 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700843 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700845 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700846 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
847 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700848 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Chris Yef59a2f42020-10-16 12:55:26 -0700852
853 case EventEntry::Type::SENSOR: {
854 std::shared_ptr<SensorEntry> sensorEntry =
855 std::static_pointer_cast<SensorEntry>(mPendingEvent);
856 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
857 dropReason = DropReason::APP_SWITCH;
858 }
859 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
860 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
861 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
862 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
863 dropReason = DropReason::STALE;
864 }
865 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
866 done = true;
867 break;
868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
870
871 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700872 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700873 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
Michael Wright3a981722015-06-10 15:26:13 +0100875 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876
877 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 }
880}
881
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882/**
883 * Return true if the events preceding this incoming motion event should be dropped
884 * Return false otherwise (the default behaviour)
885 */
886bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700888 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889
890 // Optimize case where the current application is unresponsive and the user
891 // decides to touch a window in a different application.
892 // If the application takes too long to catch up then we drop all events preceding
893 // the touch into the other window.
894 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700895 int32_t displayId = motionEntry.displayId;
896 int32_t x = static_cast<int32_t>(
897 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
898 int32_t y = static_cast<int32_t>(
899 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw3277faf2021-05-19 16:45:23 -0500900 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700901 findTouchedWindowAtLocked(displayId, x, y, nullptr);
902 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700903 touchedWindowHandle->getApplicationToken() !=
904 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700905 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700906 ALOGI("Pruning input queue because user touched a different application while waiting "
907 "for %s",
908 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700909 return true;
910 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911
912 // Alternatively, maybe there's a gesture monitor that could handle this event
913 std::vector<TouchedMonitor> gestureMonitors =
914 findTouchedGestureMonitorsLocked(displayId, {});
915 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
916 sp<Connection> connection =
917 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000918 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919 // This monitor could take more input. Drop all events preceding this
920 // event, so that gesture monitor could get a chance to receive the stream
921 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
922 "responsive gesture monitor that may handle the event",
923 mAwaitedFocusedApplication->getName().c_str());
924 return true;
925 }
926 }
927 }
928
929 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
930 // yet been processed by some connections, the dispatcher will wait for these motion
931 // events to be processed before dispatching the key event. This is because these motion events
932 // may cause a new window to be launched, which the user might expect to receive focus.
933 // To prevent waiting forever for such events, just send the key to the currently focused window
934 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
935 ALOGD("Received a new pointer down event, stop waiting for events to process and "
936 "just send the pending key event to the focused window.");
937 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700938 }
939 return false;
940}
941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700943 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700944 mInboundQueue.push_back(std::move(newEntry));
945 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 traceInboundQueueLengthLocked();
947
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700948 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700949 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 // Optimize app switch latency.
951 // If the application takes too long to catch up then we drop all events preceding
952 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700953 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700955 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700958 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700962 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 mAppSwitchSawKeyDown = false;
964 needWake = true;
965 }
966 }
967 }
968 break;
969 }
970
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700971 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
973 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700974 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100978 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700979 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
980 break;
981 }
982 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800983 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700984 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800985 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
986 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700987 // nothing to do
988 break;
989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
991
992 return needWake;
993}
994
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700995void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700996 // Do not store sensor event in recent queue to avoid flooding the queue.
997 if (entry->type != EventEntry::Type::SENSOR) {
998 mRecentQueue.push_back(entry);
999 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001000 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001001 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003}
1004
chaviw3277faf2021-05-19 16:45:23 -05001005sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1006 int32_t y, TouchState* touchState,
1007 bool addOutsideTargets,
1008 bool addPortalWindows,
1009 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001010 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1011 LOG_ALWAYS_FATAL(
1012 "Must provide a valid touch state if adding portal windows or outside targets");
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 // Traverse windows from front to back to find touched window.
chaviw3277faf2021-05-19 16:45:23 -05001015 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1016 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001017 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001018 continue;
1019 }
chaviw3277faf2021-05-19 16:45:23 -05001020 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001022 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
1024 if (windowInfo->visible) {
chaviw3277faf2021-05-19 16:45:23 -05001025 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1026 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1027 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001029 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1031 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001032 if (addPortalWindows) {
1033 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001034 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001035 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001036 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 // Found window.
1040 return windowHandle;
1041 }
1042 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001043
chaviw3277faf2021-05-19 16:45:23 -05001044 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001045 touchState->addOrUpdateWindow(windowHandle,
1046 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1047 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001052 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053}
1054
Garfield Tane84e6f92019-08-29 17:28:41 -07001055std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
chaviw3277faf2021-05-19 16:45:23 -05001056 int32_t displayId, const std::vector<sp<WindowInfoHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001057 std::vector<TouchedMonitor> touchedMonitors;
1058
1059 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1060 addGestureMonitors(monitors, touchedMonitors);
chaviw3277faf2021-05-19 16:45:23 -05001061 for (const sp<WindowInfoHandle>& portalWindow : portalWindows) {
1062 const WindowInfo* windowInfo = portalWindow->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001063 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1065 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001066 }
1067 return touchedMonitors;
1068}
1069
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001070void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 const char* reason;
1072 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001073 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 reason = "inbound event was dropped because the policy consumed it";
1078 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 case DropReason::DISABLED:
1080 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 ALOGI("Dropped event because input dispatch is disabled.");
1082 }
1083 reason = "inbound event was dropped because input dispatch is disabled";
1084 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001085 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 ALOGI("Dropped event because of pending overdue app switch.");
1087 reason = "inbound event was dropped because of pending overdue app switch";
1088 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001089 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 ALOGI("Dropped event because the current application is not responding and the user "
1091 "has started interacting with a different application.");
1092 reason = "inbound event was dropped because the current application is not responding "
1093 "and the user has started interacting with a different application";
1094 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 ALOGI("Dropped event because it is stale.");
1097 reason = "inbound event was dropped because it is stale";
1098 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001099 case DropReason::NO_POINTER_CAPTURE:
1100 ALOGI("Dropped event because there is no window with Pointer Capture.");
1101 reason = "inbound event was dropped because there is no window with Pointer Capture";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::NOT_DROPPED: {
1104 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
1108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001110 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1112 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001115 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001116 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1117 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1119 synthesizeCancelationEventsForAllConnectionsLocked(options);
1120 } else {
1121 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1122 synthesizeCancelationEventsForAllConnectionsLocked(options);
1123 }
1124 break;
1125 }
Chris Yef59a2f42020-10-16 12:55:26 -07001126 case EventEntry::Type::SENSOR: {
1127 break;
1128 }
arthurhungb89ccb02020-12-30 16:19:01 +08001129 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1130 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001131 break;
1132 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001133 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001134 case EventEntry::Type::CONFIGURATION_CHANGED:
1135 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001136 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001137 break;
1138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
1140}
1141
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001142static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1144 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145}
1146
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001147bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1148 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1149 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1150 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151}
1152
1153bool InputDispatcher::isAppSwitchPendingLocked() {
1154 return mAppSwitchDueTime != LONG_LONG_MAX;
1155}
1156
1157void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1158 mAppSwitchDueTime = LONG_LONG_MAX;
1159
1160#if DEBUG_APP_SWITCH
1161 if (handled) {
1162 ALOGD("App switch has arrived.");
1163 } else {
1164 ALOGD("App switch was abandoned.");
1165 }
1166#endif
1167}
1168
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001170 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171}
1172
1173bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001174 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 return false;
1176 }
1177
1178 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001179 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001180 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001182 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
1184 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001185 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 return true;
1187}
1188
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001189void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1190 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191}
1192
1193void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001194 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001196 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 releaseInboundEventLocked(entry);
1198 }
1199 traceInboundQueueLengthLocked();
1200}
1201
1202void InputDispatcher::releasePendingEventLocked() {
1203 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001205 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001211 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212#if DEBUG_DISPATCH_CYCLE
1213 ALOGD("Injected inbound event was dropped.");
1214#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
1217 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001218 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 }
1220 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221}
1222
1223void InputDispatcher::resetKeyRepeatLocked() {
1224 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001225 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227}
1228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1230 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231
Michael Wright2e732952014-09-24 13:26:59 -07001232 uint32_t policyFlags = entry->policyFlags &
1233 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235 std::shared_ptr<KeyEntry> newEntry =
1236 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1237 entry->source, entry->displayId, policyFlags, entry->action,
1238 entry->flags, entry->keyCode, entry->scanCode,
1239 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 newEntry->syntheticRepeat = true;
1242 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245}
1246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251#endif
1252
1253 // Reset key repeating in case a keyboard device was added or removed or something.
1254 resetKeyRepeatLocked();
1255
1256 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001257 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1258 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001259 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001260 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 return true;
1262}
1263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1265 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1268 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269#endif
1270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 synthesizeCancelationEventsForAllConnectionsLocked(options);
1274 return true;
1275}
1276
Vishnu Nairad321cd2020-08-20 16:40:21 -07001277void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001278 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001279 if (mPendingEvent != nullptr) {
1280 // Move the pending event to the front of the queue. This will give the chance
1281 // for the pending event to get dispatched to the newly focused window
1282 mInboundQueue.push_front(mPendingEvent);
1283 mPendingEvent = nullptr;
1284 }
1285
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 std::unique_ptr<FocusEntry> focusEntry =
1287 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1288 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001289
1290 // This event should go to the front of the queue, but behind all other focus events
1291 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001293 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 [](const std::shared_ptr<EventEntry>& event) {
1295 return event->type == EventEntry::Type::FOCUS;
1296 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001297
1298 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001300}
1301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001303 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001304 if (channel == nullptr) {
1305 return; // Window has gone away
1306 }
1307 InputTarget target;
1308 target.inputChannel = channel;
1309 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1310 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001311 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1312 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001313 std::string reason = std::string("reason=").append(entry->reason);
1314 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001315 dispatchEventLocked(currentTime, entry, {target});
1316}
1317
Prabir Pradhan99987712020-11-10 18:43:05 -08001318void InputDispatcher::dispatchPointerCaptureChangedLocked(
1319 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1320 DropReason& dropReason) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00001321 dropReason = DropReason::NOT_DROPPED;
1322
Prabir Pradhan99987712020-11-10 18:43:05 -08001323 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001324 sp<IBinder> token;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001325
1326 if (entry->pointerCaptureRequest.enable) {
1327 // Enable Pointer Capture.
1328 if (haveWindowWithPointerCapture &&
1329 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1330 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1331 "to the window.");
1332 }
1333 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001334 // This can happen if a window requests capture and immediately releases capture.
1335 ALOGW("No window requested Pointer Capture.");
Prabir Pradhanac483a62021-08-06 14:01:18 +00001336 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001337 return;
1338 }
Prabir Pradhanac483a62021-08-06 14:01:18 +00001339 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1340 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1341 return;
1342 }
1343
Vishnu Nairc519ff72021-01-21 08:23:08 -08001344 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1346 mWindowTokenWithPointerCapture = token;
1347 } else {
Prabir Pradhanac483a62021-08-06 14:01:18 +00001348 // Disable Pointer Capture.
1349 // We do not check if the sequence number matches for requests to disable Pointer Capture
1350 // for two reasons:
1351 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1352 // to disable capture with the same sequence number: one generated by
1353 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1354 // Capture being disabled in InputReader.
1355 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1356 // actual Pointer Capture state that affects events being generated by input devices is
1357 // in InputReader.
1358 if (!haveWindowWithPointerCapture) {
1359 // Pointer capture was already forcefully disabled because of focus change.
1360 dropReason = DropReason::NOT_DROPPED;
1361 return;
1362 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001363 token = mWindowTokenWithPointerCapture;
1364 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001365 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001366 setPointerCaptureLocked(false);
1367 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 }
1369
1370 auto channel = getInputChannelLocked(token);
1371 if (channel == nullptr) {
1372 // Window has gone away, clean up Pointer Capture state.
1373 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhanac483a62021-08-06 14:01:18 +00001374 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001375 setPointerCaptureLocked(false);
1376 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001377 return;
1378 }
1379 InputTarget target;
1380 target.inputChannel = channel;
1381 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1382 entry->dispatchInProgress = true;
1383 dispatchEventLocked(currentTime, entry, {target});
1384
1385 dropReason = DropReason::NOT_DROPPED;
1386}
1387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001388bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 if (!entry->dispatchInProgress) {
1392 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1393 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1394 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1395 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001396 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 // We have seen two identical key downs in a row which indicates that the device
1398 // driver is automatically generating key repeats itself. We take note of the
1399 // repeat here, but we disable our own next key repeat timer since it is clear that
1400 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001401 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1402 // Make sure we don't get key down from a different device. If a different
1403 // device Id has same key pressed down, the new device Id will replace the
1404 // current one to hold the key repeat with repeat count reset.
1405 // In the future when got a KEY_UP on the device id, drop it and do not
1406 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1408 resetKeyRepeatLocked();
1409 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1410 } else {
1411 // Not a repeat. Save key down state in case we do see a repeat later.
1412 resetKeyRepeatLocked();
1413 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1414 }
1415 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001416 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1417 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001419#if DEBUG_INBOUND_EVENT_DETAILS
1420 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1421#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 resetKeyRepeatLocked();
1424 }
1425
1426 if (entry->repeatCount == 1) {
1427 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1428 } else {
1429 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1430 }
1431
1432 entry->dispatchInProgress = true;
1433
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001434 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436
1437 // Handle case where the policy asked us to try again later last time.
1438 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1439 if (currentTime < entry->interceptKeyWakeupTime) {
1440 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1441 *nextWakeupTime = entry->interceptKeyWakeupTime;
1442 }
1443 return false; // wait until next wakeup
1444 }
1445 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1446 entry->interceptKeyWakeupTime = 0;
1447 }
1448
1449 // Give the policy a chance to intercept the key.
1450 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1451 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001452 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001453 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001454 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001455 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001456 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001458 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 return false; // wait for the command to run
1460 } else {
1461 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1462 }
1463 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001464 if (*dropReason == DropReason::NOT_DROPPED) {
1465 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467 }
1468
1469 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001470 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001471 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1473 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001474 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 return true;
1476 }
1477
1478 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001479 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001480 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001482 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 return false;
1484 }
1485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001486 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return true;
1489 }
1490
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001491 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001492 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493
1494 // Dispatch the key.
1495 dispatchEventLocked(currentTime, entry, inputTargets);
1496 return true;
1497}
1498
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001499void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001501 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001502 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1503 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1505 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1506 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507#endif
1508}
1509
Chris Yef59a2f42020-10-16 12:55:26 -07001510void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1511 mLock.unlock();
1512
1513 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1514 if (entry->accuracyChanged) {
1515 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1516 }
1517 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1518 entry->hwTimestamp, entry->values);
1519 mLock.lock();
1520}
1521
1522void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1523 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1524#if DEBUG_OUTBOUND_EVENT_DETAILS
1525 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1526 "source=0x%x, sensorType=%s",
1527 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001528 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001529#endif
1530 std::unique_ptr<CommandEntry> commandEntry =
1531 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1532 commandEntry->sensorEntry = entry;
1533 postCommandLocked(std::move(commandEntry));
1534}
1535
1536bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1537#if DEBUG_OUTBOUND_EVENT_DETAILS
1538 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1539 NamedEnum::string(sensorType).c_str());
1540#endif
1541 { // acquire lock
1542 std::scoped_lock _l(mLock);
1543
1544 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1545 std::shared_ptr<EventEntry> entry = *it;
1546 if (entry->type == EventEntry::Type::SENSOR) {
1547 it = mInboundQueue.erase(it);
1548 releaseInboundEventLocked(entry);
1549 }
1550 }
1551 }
1552 return true;
1553}
1554
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001556 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001557 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 entry->dispatchInProgress = true;
1561
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 }
1564
1565 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001566 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001567 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001568 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1569 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return true;
1571 }
1572
1573 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1574
1575 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001576 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
1578 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001579 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 if (isPointerEvent) {
1581 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001584 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 } else {
1586 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001590 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 return false;
1592 }
1593
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001594 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001595 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001596 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1597 return true;
1598 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001599 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001600 CancelationOptions::Mode mode(isPointerEvent
1601 ? CancelationOptions::CANCEL_POINTER_EVENTS
1602 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1603 CancelationOptions options(mode, "input event injection failed");
1604 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 return true;
1606 }
1607
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001608 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001611 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001612 std::unordered_map<int32_t, TouchState>::iterator it =
1613 mTouchStatesByDisplay.find(entry->displayId);
1614 if (it != mTouchStatesByDisplay.end()) {
1615 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001616 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001617 // The event has gone through these portal windows, so we add monitoring targets of
1618 // the corresponding displays as well.
1619 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05001620 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001621 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001622 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001623 }
1624 }
1625 }
1626 }
1627
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 // Dispatch the motion.
1629 if (conflictingPointerActions) {
1630 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001631 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 synthesizeCancelationEventsForAllConnectionsLocked(options);
1633 }
1634 dispatchEventLocked(currentTime, entry, inputTargets);
1635 return true;
1636}
1637
chaviw3277faf2021-05-19 16:45:23 -05001638void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001639 bool isExiting, const MotionEntry& motionEntry) {
1640 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1641 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1642 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1643 PointerCoords pointerCoords;
1644 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1645 pointerCoords.transform(windowHandle->getInfo()->transform);
1646
1647 std::unique_ptr<DragEntry> dragEntry =
1648 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1649 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1650 pointerCoords.getY());
1651
1652 enqueueInboundEventLocked(std::move(dragEntry));
1653}
1654
1655void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1656 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1657 if (channel == nullptr) {
1658 return; // Window has gone away
1659 }
1660 InputTarget target;
1661 target.inputChannel = channel;
1662 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1663 entry->dispatchInProgress = true;
1664 dispatchEventLocked(currentTime, entry, {target});
1665}
1666
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001669 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 ", policyFlags=0x%x, "
1671 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1672 "metaState=0x%x, buttonState=0x%x,"
1673 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1675 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1676 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001678 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 "x=%f, y=%f, pressure=%f, size=%f, "
1681 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1682 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1684 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1685 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1686 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1687 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1688 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1689 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1690 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1691 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1692 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
1694#endif
1695}
1696
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001697void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1698 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001699 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001700 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701#if DEBUG_DISPATCH_CYCLE
1702 ALOGD("dispatchEventToCurrentInputTargets");
1703#endif
1704
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001705 updateInteractionTokensLocked(*eventEntry, inputTargets);
1706
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1708
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001709 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001711 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001712 sp<Connection> connection =
1713 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001714 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001715 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001717 if (DEBUG_FOCUS) {
1718 ALOGD("Dropping event delivery to target with channel '%s' because it "
1719 "is no longer registered with the input dispatcher.",
1720 inputTarget.inputChannel->getName().c_str());
1721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 }
1723 }
1724}
1725
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001726void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1727 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1728 // If the policy decides to close the app, we will get a channel removal event via
1729 // unregisterInputChannel, and will clean up the connection that way. We are already not
1730 // sending new pointers to the connection when it blocked, but focused events will continue to
1731 // pile up.
1732 ALOGW("Canceling events for %s because it is unresponsive",
1733 connection->inputChannel->getName().c_str());
1734 if (connection->status == Connection::STATUS_NORMAL) {
1735 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1736 "application not responding");
1737 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739}
1740
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001742 if (DEBUG_FOCUS) {
1743 ALOGD("Resetting ANR timeouts.");
1744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
1746 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001747 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001748 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749}
1750
Tiger Huang721e26f2018-07-24 22:26:19 +08001751/**
1752 * Get the display id that the given event should go to. If this event specifies a valid display id,
1753 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1754 * Focused display is the display that the user most recently interacted with.
1755 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001757 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001758 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001759 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001760 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1761 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 break;
1763 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001764 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1766 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 break;
1768 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001769 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001770 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001771 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001772 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001773 case EventEntry::Type::SENSOR:
1774 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001775 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 return ADISPLAY_ID_NONE;
1777 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001778 }
1779 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1780}
1781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1783 const char* focusedWindowName) {
1784 if (mAnrTracker.empty()) {
1785 // already processed all events that we waited for
1786 mKeyIsWaitingForEventsTimeout = std::nullopt;
1787 return false;
1788 }
1789
1790 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1791 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001792 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001793 mKeyIsWaitingForEventsTimeout = currentTime +
1794 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1795 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796 return true;
1797 }
1798
1799 // We still have pending events, and already started the timer
1800 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1801 return true; // Still waiting
1802 }
1803
1804 // Waited too long, and some connection still hasn't processed all motions
1805 // Just send the key to the focused window
1806 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1807 focusedWindowName);
1808 mKeyIsWaitingForEventsTimeout = std::nullopt;
1809 return false;
1810}
1811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001812InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1813 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1814 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001815 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
Tiger Huang721e26f2018-07-24 22:26:19 +08001817 int32_t displayId = getTargetDisplayId(entry);
chaviw3277faf2021-05-19 16:45:23 -05001818 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001819 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001820 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1821
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 // If there is no currently focused window and no focused application
1823 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001824 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1825 ALOGI("Dropping %s event because there is no focused window or focused application in "
1826 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001827 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001828 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830
Vishnu Nair41f77b82021-09-03 16:07:44 -07001831 // Drop key events if requested by input feature
1832 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1833 return InputEventInjectionResult::FAILED;
1834 }
1835
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1837 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1838 // start interacting with another application via touch (app switch). This code can be removed
1839 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1840 // an app is expected to have a focused window.
1841 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1842 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1843 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001844 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1845 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1846 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001847 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001848 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 ALOGW("Waiting because no window has focus but %s may eventually add a "
1850 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001851 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1855 // Already raised ANR. Drop the event
1856 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001857 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001859 } else {
1860 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001862 }
1863 }
1864
1865 // we have a valid, non-null focused window
1866 resetNoFocusedWindowTimeoutLocked();
1867
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001869 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001870 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001873 if (focusedWindowHandle->getInfo()->paused) {
1874 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001876 }
1877
1878 // If the event is a key event, then we must wait for all previous events to
1879 // complete before delivering it because previous events may have the
1880 // side-effect of transferring focus to a different window and we want to
1881 // ensure that the following keys are sent to the new window.
1882 //
1883 // Suppose the user touches a button in a window then immediately presses "A".
1884 // If the button causes a pop-up window to appear then we want to ensure that
1885 // the "A" key is delivered to the new pop-up window. This is because users
1886 // often anticipate pending UI changes when typing on a keyboard.
1887 // To obtain this behavior, we must serialize key events with respect to all
1888 // prior input events.
1889 if (entry.type == EventEntry::Type::KEY) {
1890 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1891 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 }
1895
1896 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001897 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001898 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1899 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900
1901 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903}
1904
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905/**
1906 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1907 * that are currently unresponsive.
1908 */
1909std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1910 const std::vector<TouchedMonitor>& monitors) const {
1911 std::vector<TouchedMonitor> responsiveMonitors;
1912 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1913 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1914 sp<Connection> connection = getConnectionLocked(
1915 monitor.monitor.inputChannel->getConnectionToken());
1916 if (connection == nullptr) {
1917 ALOGE("Could not find connection for monitor %s",
1918 monitor.monitor.inputChannel->getName().c_str());
1919 return false;
1920 }
1921 if (!connection->responsive) {
1922 ALOGW("Unresponsive monitor %s will not get the new gesture",
1923 connection->inputChannel->getName().c_str());
1924 return false;
1925 }
1926 return true;
1927 });
1928 return responsiveMonitors;
1929}
1930
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001931InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1932 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1933 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001934 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 enum InjectionPermission {
1936 INJECTION_PERMISSION_UNKNOWN,
1937 INJECTION_PERMISSION_GRANTED,
1938 INJECTION_PERMISSION_DENIED
1939 };
1940
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 // For security reasons, we defer updating the touch state until we are sure that
1942 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943 int32_t displayId = entry.displayId;
1944 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1946
1947 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001948 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw3277faf2021-05-19 16:45:23 -05001950 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1951 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001953 // Copy current touch state into tempTouchState.
1954 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1955 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001956 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001957 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001958 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1959 mTouchStatesByDisplay.find(displayId);
1960 if (oldStateIt != mTouchStatesByDisplay.end()) {
1961 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001962 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001963 }
1964
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001965 bool isSplit = tempTouchState.split;
1966 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1967 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1968 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1970 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1971 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1972 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1973 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001974 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 bool wrongDevice = false;
1976 if (newGesture) {
1977 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001979 ALOGI("Dropping event because a pointer for a different device is already down "
1980 "in display %" PRId32,
1981 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001982 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 switchedDevice = false;
1985 wrongDevice = true;
1986 goto Failed;
1987 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 tempTouchState.reset();
1989 tempTouchState.down = down;
1990 tempTouchState.deviceId = entry.deviceId;
1991 tempTouchState.source = entry.source;
1992 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001994 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001995 ALOGI("Dropping move event because a pointer for a different device is already active "
1996 "in display %" PRId32,
1997 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001998 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002000 switchedDevice = false;
2001 wrongDevice = true;
2002 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
2004
2005 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2006 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2007
Garfield Tan00f511d2019-06-12 16:55:40 -07002008 int32_t x;
2009 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002011 // Always dispatch mouse events to cursor position.
2012 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002013 x = int32_t(entry.xCursorPosition);
2014 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002015 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2017 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002018 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002019 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07002020 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002021 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2022 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002023
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 if (newTouchedWindowHandle != nullptr &&
2026 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002027 // New window supports splitting, but we should never split mouse events.
2028 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 } else if (isSplit) {
2030 // New window does not support splitting but we have already split events.
2031 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002032 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034
2035 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002036 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002038 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002039 }
2040
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2042 ALOGI("Not sending touch event to %s because it is paused",
2043 newTouchedWindowHandle->getName().c_str());
2044 newTouchedWindowHandle = nullptr;
2045 }
2046
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002047 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002048 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002049 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2050 if (!isResponsive) {
2051 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2053 newTouchedWindowHandle = nullptr;
2054 }
2055 }
2056
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002057 // Drop events that can't be trusted due to occlusion
2058 if (newTouchedWindowHandle != nullptr &&
2059 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2060 TouchOcclusionInfo occlusionInfo =
2061 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002062 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002063 if (DEBUG_TOUCH_OCCLUSION) {
2064 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2065 for (const auto& log : occlusionInfo.debugInfo) {
2066 ALOGD("%s", log.c_str());
2067 }
2068 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002069 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2070 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2071 ALOGW("Dropping untrusted touch event due to %s/%d",
2072 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2073 newTouchedWindowHandle = nullptr;
2074 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002075 }
2076 }
2077
Vishnu Nair41f77b82021-09-03 16:07:44 -07002078 // Drop touch events if requested by input feature
2079 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2080 newTouchedWindowHandle = nullptr;
2081 }
2082
Arthur Hung71625472021-11-16 02:45:54 +00002083 const std::vector<TouchedMonitor> newGestureMonitors = isDown
2084 ? selectResponsiveMonitorsLocked(
2085 findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows))
2086 : tempTouchState.gestureMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002087
Michael Wright3dd60e22019-03-27 22:06:44 +00002088 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2089 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002090 "(%d, %d) in display %" PRId32 ".",
2091 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002093 goto Failed;
2094 }
2095
2096 if (newTouchedWindowHandle != nullptr) {
2097 // Set target flags.
2098 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2099 if (isSplit) {
2100 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002102 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2103 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2104 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2105 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2106 }
2107
2108 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002109 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2110 newHoverWindowHandle = nullptr;
2111 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002112 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 }
2114
2115 // Update the temporary touch state.
2116 BitSet32 pointerIds;
2117 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002118 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 pointerIds.markBit(pointerId);
2120 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002121 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Arthur Hung71625472021-11-16 02:45:54 +00002122 } else if (tempTouchState.windows.empty()) {
2123 // If no window is touched, set split to true. This will allow the next pointer down to
2124 // be delivered to a new window which supports split touch.
2125 tempTouchState.split = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
Arthur Hung71625472021-11-16 02:45:54 +00002127 if (isDown) {
2128 tempTouchState.addGestureMonitors(newGestureMonitors);
2129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 } else {
2131 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2132
2133 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002134 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002135 if (DEBUG_FOCUS) {
2136 ALOGD("Dropping event because the pointer is not down or we previously "
2137 "dropped the pointer down event in display %" PRId32,
2138 displayId);
2139 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002140 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 goto Failed;
2142 }
2143
arthurhung6d4bed92021-03-17 11:59:33 +08002144 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002145
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002147 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2150 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
chaviw3277faf2021-05-19 16:45:23 -05002152 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002154 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair41f77b82021-09-03 16:07:44 -07002155
2156 // Drop touch events if requested by input feature
2157 if (newTouchedWindowHandle != nullptr &&
2158 shouldDropInput(entry, newTouchedWindowHandle)) {
2159 newTouchedWindowHandle = nullptr;
2160 }
2161
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002162 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2163 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002164 if (DEBUG_FOCUS) {
2165 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2166 oldTouchedWindowHandle->getName().c_str(),
2167 newTouchedWindowHandle->getName().c_str(), displayId);
2168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002170 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2171 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2172 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173
2174 // Make a slippery entrance into the new window.
2175 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2176 isSplit = true;
2177 }
2178
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 int32_t targetFlags =
2180 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 if (isSplit) {
2182 targetFlags |= InputTarget::FLAG_SPLIT;
2183 }
2184 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2185 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002186 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2187 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
2189
2190 BitSet32 pointerIds;
2191 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196 }
2197 }
2198
2199 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002200 // Let the previous window know that the hover sequence is over, unless we already did it
2201 // when dispatching it as is to newTouchedWindowHandle.
2202 if (mLastHoverWindowHandle != nullptr &&
2203 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2204 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205#if DEBUG_HOVER
2206 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002207 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2210 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
Garfield Tandf26e862020-07-01 20:18:19 -07002213 // Let the new window know that the hover sequence is starting, unless we already did it
2214 // when dispatching it as is to newTouchedWindowHandle.
2215 if (newHoverWindowHandle != nullptr &&
2216 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2217 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218#if DEBUG_HOVER
2219 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002222 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2223 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2224 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226 }
2227
2228 // Check permission to inject into all touched foreground windows and ensure there
2229 // is at least one touched foreground window.
2230 {
2231 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2234 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002235 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002236 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 injectionPermission = INJECTION_PERMISSION_DENIED;
2238 goto Failed;
2239 }
2240 }
2241 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002243 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002244 ALOGI("Dropping event because there is no touched foreground window in display "
2245 "%" PRId32 " or gesture monitor to receive it.",
2246 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002247 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 goto Failed;
2249 }
2250
2251 // Permission granted to injection into all touched foreground windows.
2252 injectionPermission = INJECTION_PERMISSION_GRANTED;
2253 }
2254
2255 // Check whether windows listening for outside touches are owned by the same UID. If it is
2256 // set the policy flag that we will not reveal coordinate information to this window.
2257 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002258 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002259 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 if (foregroundWindowHandle) {
2261 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002262 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw3277faf2021-05-19 16:45:23 -05002264 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2265 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2266 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 InputTarget::FLAG_ZERO_COORDS,
2268 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271 }
2272 }
2273 }
2274
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // If this is the first pointer going down and the touched window has a wallpaper
2276 // then also add the touched wallpaper windows so they are locked in for the duration
2277 // of the touch gesture.
2278 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2279 // engine only supports touch events. We would need to add a mechanism similar
2280 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2281 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw3277faf2021-05-19 16:45:23 -05002282 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw3277faf2021-05-19 16:45:23 -05002285 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002286 getWindowHandlesLocked(displayId);
chaviw3277faf2021-05-19 16:45:23 -05002287 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2288 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 if (info->displayId == displayId &&
chaviw3277faf2021-05-19 16:45:23 -05002290 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002291 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292 .addOrUpdateWindow(windowHandle,
2293 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2294 InputTarget::
2295 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2296 InputTarget::FLAG_DISPATCH_AS_IS,
2297 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299 }
2300 }
2301 }
2302
2303 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002304 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002306 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
2310
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002312 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002314 }
2315
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 // Drop the outside or hover touch windows since we will not care about them
2317 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002318 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
2320Failed:
2321 // Check injection permission once and for all.
2322 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002323 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 injectionPermission = INJECTION_PERMISSION_GRANTED;
2325 } else {
2326 injectionPermission = INJECTION_PERMISSION_DENIED;
2327 }
2328 }
2329
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002330 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2331 return injectionResult;
2332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002335 if (!wrongDevice) {
2336 if (switchedDevice) {
2337 if (DEBUG_FOCUS) {
2338 ALOGD("Conflicting pointer actions: Switched to a different device.");
2339 }
2340 *outConflictingPointerActions = true;
2341 }
2342
2343 if (isHoverAction) {
2344 // Started hovering, therefore no longer down.
2345 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002346 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002347 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2348 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 *outConflictingPointerActions = true;
2351 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002352 tempTouchState.reset();
2353 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2354 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2355 tempTouchState.deviceId = entry.deviceId;
2356 tempTouchState.source = entry.source;
2357 tempTouchState.displayId = displayId;
2358 }
2359 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2360 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2361 // All pointers up or canceled.
2362 tempTouchState.reset();
2363 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2364 // First pointer went down.
2365 if (oldState && oldState->down) {
2366 if (DEBUG_FOCUS) {
2367 ALOGD("Conflicting pointer actions: Down received while already down.");
2368 }
2369 *outConflictingPointerActions = true;
2370 }
2371 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2372 // One pointer went up.
2373 if (isSplit) {
2374 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2375 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002377 for (size_t i = 0; i < tempTouchState.windows.size();) {
2378 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2379 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2380 touchedWindow.pointerIds.clearBit(pointerId);
2381 if (touchedWindow.pointerIds.isEmpty()) {
2382 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2383 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002386 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002388 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002389 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002390
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002391 // Save changes unless the action was scroll in which case the temporary touch
2392 // state was only valid for this one action.
2393 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2394 if (tempTouchState.displayId >= 0) {
2395 mTouchStatesByDisplay[displayId] = tempTouchState;
2396 } else {
2397 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002401 // Update hover state.
2402 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
2404
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 return injectionResult;
2406}
2407
arthurhung6d4bed92021-03-17 11:59:33 +08002408void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw3277faf2021-05-19 16:45:23 -05002409 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002410 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2411 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2412 true /*ignoreDragWindow*/);
2413 if (dropWindow) {
2414 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2415 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002416 } else {
2417 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002418 }
2419 mDragState.reset();
2420}
2421
2422void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2423 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002424 return;
2425 }
2426
arthurhung6d4bed92021-03-17 11:59:33 +08002427 if (!mDragState->isStartDrag) {
2428 mDragState->isStartDrag = true;
2429 mDragState->isStylusButtonDownAtStart =
2430 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2431 }
2432
arthurhungb89ccb02020-12-30 16:19:01 +08002433 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2434 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2435 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2436 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002437 // Handle the special case : stylus button no longer pressed.
2438 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2439 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2440 finishDragAndDrop(entry.displayId, x, y);
2441 return;
2442 }
2443
chaviw3277faf2021-05-19 16:45:23 -05002444 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002445 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002446 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2447 true /*ignoreDragWindow*/);
2448 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002449 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2450 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2451 if (mDragState->dragHoverWindowHandle != nullptr) {
2452 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2453 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002454 }
arthurhung6d4bed92021-03-17 11:59:33 +08002455 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002456 }
2457 // enqueue drag location if needed.
2458 if (hoverWindowHandle != nullptr) {
2459 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2460 }
arthurhung6d4bed92021-03-17 11:59:33 +08002461 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2462 finishDragAndDrop(entry.displayId, x, y);
2463 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002464 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002465 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002466 }
2467}
2468
chaviw3277faf2021-05-19 16:45:23 -05002469void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002470 int32_t targetFlags, BitSet32 pointerIds,
2471 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002472 std::vector<InputTarget>::iterator it =
2473 std::find_if(inputTargets.begin(), inputTargets.end(),
2474 [&windowHandle](const InputTarget& inputTarget) {
2475 return inputTarget.inputChannel->getConnectionToken() ==
2476 windowHandle->getToken();
2477 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002478
chaviw3277faf2021-05-19 16:45:23 -05002479 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002480
2481 if (it == inputTargets.end()) {
2482 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002483 std::shared_ptr<InputChannel> inputChannel =
2484 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002485 if (inputChannel == nullptr) {
2486 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2487 return;
2488 }
2489 inputTarget.inputChannel = inputChannel;
2490 inputTarget.flags = targetFlags;
2491 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002492 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002493 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002494 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002495 inputTargets.push_back(inputTarget);
2496 it = inputTargets.end() - 1;
2497 }
2498
2499 ALOG_ASSERT(it->flags == targetFlags);
2500 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2501
chaviw1ff3d1e2020-07-01 15:53:47 -07002502 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503}
2504
Michael Wright3dd60e22019-03-27 22:06:44 +00002505void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 int32_t displayId, float xOffset,
2507 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002508 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2509 mGlobalMonitorsByDisplay.find(displayId);
2510
2511 if (it != mGlobalMonitorsByDisplay.end()) {
2512 const std::vector<Monitor>& monitors = it->second;
2513 for (const Monitor& monitor : monitors) {
2514 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517}
2518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002519void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2520 float yOffset,
2521 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002522 InputTarget target;
2523 target.inputChannel = monitor.inputChannel;
2524 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002525 ui::Transform t;
2526 t.set(xOffset, yOffset);
2527 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002528 inputTargets.push_back(target);
2529}
2530
chaviw3277faf2021-05-19 16:45:23 -05002531bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 const InjectionState* injectionState) {
2533 if (injectionState &&
2534 (windowHandle == nullptr ||
2535 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2536 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002537 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 "owned by uid %d",
2540 injectionState->injectorPid, injectionState->injectorUid,
2541 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 } else {
2543 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 }
2546 return false;
2547 }
2548 return true;
2549}
2550
Robert Carrc9bf1d32020-04-13 17:21:08 -07002551/**
2552 * Indicate whether one window handle should be considered as obscuring
2553 * another window handle. We only check a few preconditions. Actually
2554 * checking the bounds is left to the caller.
2555 */
chaviw3277faf2021-05-19 16:45:23 -05002556static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2557 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002558 // Compare by token so cloned layers aren't counted
2559 if (haveSameToken(windowHandle, otherHandle)) {
2560 return false;
2561 }
2562 auto info = windowHandle->getInfo();
2563 auto otherInfo = otherHandle->getInfo();
2564 if (!otherInfo->visible) {
2565 return false;
chaviw3277faf2021-05-19 16:45:23 -05002566 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002567 // Those act as if they were invisible, so we don't need to flag them.
2568 // We do want to potentially flag touchable windows even if they have 0
2569 // opacity, since they can consume touches and alter the effects of the
2570 // user interaction (eg. apps that rely on
2571 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2572 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2573 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002574 } else if (info->ownerUid == otherInfo->ownerUid) {
2575 // If ownerUid is the same we don't generate occlusion events as there
2576 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002577 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002578 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002579 return false;
2580 } else if (otherInfo->displayId != info->displayId) {
2581 return false;
2582 }
2583 return true;
2584}
2585
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002586/**
2587 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2588 * untrusted, one should check:
2589 *
2590 * 1. If result.hasBlockingOcclusion is true.
2591 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2592 * BLOCK_UNTRUSTED.
2593 *
2594 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2595 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2596 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2597 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2598 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2599 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2600 *
2601 * If neither of those is true, then it means the touch can be allowed.
2602 */
2603InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw3277faf2021-05-19 16:45:23 -05002604 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2605 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002606 int32_t displayId = windowInfo->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002607 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002608 TouchOcclusionInfo info;
2609 info.hasBlockingOcclusion = false;
2610 info.obscuringOpacity = 0;
2611 info.obscuringUid = -1;
2612 std::map<int32_t, float> opacityByUid;
chaviw3277faf2021-05-19 16:45:23 -05002613 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002614 if (windowHandle == otherHandle) {
2615 break; // All future windows are below us. Exit early.
2616 }
chaviw3277faf2021-05-19 16:45:23 -05002617 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002618 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2619 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002620 if (DEBUG_TOUCH_OCCLUSION) {
2621 info.debugInfo.push_back(
2622 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2623 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002624 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2625 // we perform the checks below to see if the touch can be propagated or not based on the
2626 // window's touch occlusion mode
2627 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2628 info.hasBlockingOcclusion = true;
2629 info.obscuringUid = otherInfo->ownerUid;
2630 info.obscuringPackage = otherInfo->packageName;
2631 break;
2632 }
2633 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2634 uint32_t uid = otherInfo->ownerUid;
2635 float opacity =
2636 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2637 // Given windows A and B:
2638 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2639 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2640 opacityByUid[uid] = opacity;
2641 if (opacity > info.obscuringOpacity) {
2642 info.obscuringOpacity = opacity;
2643 info.obscuringUid = uid;
2644 info.obscuringPackage = otherInfo->packageName;
2645 }
2646 }
2647 }
2648 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002649 if (DEBUG_TOUCH_OCCLUSION) {
2650 info.debugInfo.push_back(
2651 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2652 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002653 return info;
2654}
2655
chaviw3277faf2021-05-19 16:45:23 -05002656std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002657 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002658 return StringPrintf(INDENT2
2659 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2660 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2661 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2662 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002663 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002664 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002665 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002666 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2667 info->frameTop, info->frameRight, info->frameBottom,
2668 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002669 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2670 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2671 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002672}
2673
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002674bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2675 if (occlusionInfo.hasBlockingOcclusion) {
2676 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2677 occlusionInfo.obscuringUid);
2678 return false;
2679 }
2680 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2681 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2682 "%.2f, maximum allowed = %.2f)",
2683 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2684 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2685 return false;
2686 }
2687 return true;
2688}
2689
chaviw3277faf2021-05-19 16:45:23 -05002690bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002693 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2694 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002695 if (windowHandle == otherHandle) {
2696 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 }
chaviw3277faf2021-05-19 16:45:23 -05002698 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002699 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002700 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 return true;
2702 }
2703 }
2704 return false;
2705}
2706
chaviw3277faf2021-05-19 16:45:23 -05002707bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002708 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw3277faf2021-05-19 16:45:23 -05002709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2710 const WindowInfo* windowInfo = windowHandle->getInfo();
2711 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 if (windowHandle == otherHandle) {
2713 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002714 }
chaviw3277faf2021-05-19 16:45:23 -05002715 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002716 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002717 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002718 return true;
2719 }
2720 }
2721 return false;
2722}
2723
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002724std::string InputDispatcher::getApplicationWindowLabel(
chaviw3277faf2021-05-19 16:45:23 -05002725 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002726 if (applicationHandle != nullptr) {
2727 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002728 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 } else {
2730 return applicationHandle->getName();
2731 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002732 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002733 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002735 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737}
2738
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002739void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002740 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002741 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2742 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002743 // Focus or pointer capture changed events are passed to apps, but do not represent user
2744 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002745 return;
2746 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002747 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw3277faf2021-05-19 16:45:23 -05002748 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002749 if (focusedWindowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05002750 const WindowInfo* info = focusedWindowHandle->getInfo();
2751 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002753 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754#endif
2755 return;
2756 }
2757 }
2758
2759 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002760 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002761 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2763 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 return;
2765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002767 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 eventType = USER_ACTIVITY_EVENT_TOUCH;
2769 }
2770 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002772 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002773 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2774 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 return;
2776 }
2777 eventType = USER_ACTIVITY_EVENT_BUTTON;
2778 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002780 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002781 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002782 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002783 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002784 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2785 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002786 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002787 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002788 break;
2789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
2791
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002792 std::unique_ptr<CommandEntry> commandEntry =
2793 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002794 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002796 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002797 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798}
2799
2800void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002802 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002803 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002804 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002806 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002807 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002808 ATRACE_NAME(message.c_str());
2809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810#if DEBUG_DISPATCH_CYCLE
2811 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002812 "globalScaleFactor=%f, pointerIds=0x%x %s",
2813 connection->getInputChannelName().c_str(), inputTarget.flags,
2814 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2815 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816#endif
2817
2818 // Skip this event if the connection status is not normal.
2819 // We don't want to enqueue additional outbound events if the connection is broken.
2820 if (connection->status != Connection::STATUS_NORMAL) {
2821#if DEBUG_DISPATCH_CYCLE
2822 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824#endif
2825 return;
2826 }
2827
2828 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002829 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2830 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2831 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002832 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002834 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002835 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002836 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002837 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 if (!splitMotionEntry) {
2839 return; // split event was dropped
2840 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002841 if (DEBUG_FOCUS) {
2842 ALOGD("channel '%s' ~ Split motion event.",
2843 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002844 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002845 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002846 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2847 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 return;
2849 }
2850 }
2851
2852 // Not splitting. Enqueue dispatch entries for the event as is.
2853 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2854}
2855
2856void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002858 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002859 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002860 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002862 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002863 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002864 ATRACE_NAME(message.c_str());
2865 }
2866
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002867 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868
2869 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002870 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002872 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002873 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002874 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002876 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002878 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002880 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
2883 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002884 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 startDispatchCycleLocked(currentTime, connection);
2886 }
2887}
2888
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002890 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002891 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002893 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2895 connection->getInputChannelName().c_str(),
2896 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002897 ATRACE_NAME(message.c_str());
2898 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002899 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 if (!(inputTargetFlags & dispatchMode)) {
2901 return;
2902 }
2903 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2904
2905 // This is a new event.
2906 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002907 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002908 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002910 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2911 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002912 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002914 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002915 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002916 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002917 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002918 dispatchEntry->resolvedAction = keyEntry.action;
2919 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2922 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2925 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 return; // skip the inconsistent event
2928 }
2929 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002932 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002933 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002934 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2935 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2936 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2937 static_cast<int32_t>(IdGenerator::Source::OTHER);
2938 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2940 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2941 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2942 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2943 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2944 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2945 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2946 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2947 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2948 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2949 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002951 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 }
2953 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002954 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2955 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2958 "event",
2959 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002961 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2962 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2968 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2969 }
2970 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2971 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2975 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2978 "event",
2979 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 return; // skip the inconsistent event
2982 }
2983
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 dispatchEntry->resolvedEventId =
2985 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2986 ? mIdGenerator.nextId()
2987 : motionEntry.id;
2988 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2989 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2990 ") to MotionEvent(id=0x%" PRIx32 ").",
2991 motionEntry.id, dispatchEntry->resolvedEventId);
2992 ATRACE_NAME(message.c_str());
2993 }
2994
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002995 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2996 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2997 // Skip reporting pointer down outside focus to the policy.
2998 break;
2999 }
3000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003001 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003002 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003
3004 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003006 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003007 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3008 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003009 break;
3010 }
Chris Yef59a2f42020-10-16 12:55:26 -07003011 case EventEntry::Type::SENSOR: {
3012 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3013 break;
3014 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003015 case EventEntry::Type::CONFIGURATION_CHANGED:
3016 case EventEntry::Type::DEVICE_RESET: {
3017 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07003018 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003019 break;
3020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
3022
3023 // Remember that we are waiting for this dispatch to complete.
3024 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003025 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
3027
3028 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003029 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003030 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003031}
3032
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003033/**
3034 * This function is purely for debugging. It helps us understand where the user interaction
3035 * was taking place. For example, if user is touching launcher, we will see a log that user
3036 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3037 * We will see both launcher and wallpaper in that list.
3038 * Once the interaction with a particular set of connections starts, no new logs will be printed
3039 * until the set of interacted connections changes.
3040 *
3041 * The following items are skipped, to reduce the logspam:
3042 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3043 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3044 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3045 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3046 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003047 */
3048void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3049 const std::vector<InputTarget>& targets) {
3050 // Skip ACTION_UP events, and all events other than keys and motions
3051 if (entry.type == EventEntry::Type::KEY) {
3052 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3053 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3054 return;
3055 }
3056 } else if (entry.type == EventEntry::Type::MOTION) {
3057 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3058 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3059 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3060 return;
3061 }
3062 } else {
3063 return; // Not a key or a motion
3064 }
3065
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003066 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003067 std::vector<sp<Connection>> newConnections;
3068 for (const InputTarget& target : targets) {
3069 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3070 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3071 continue; // Skip windows that receive ACTION_OUTSIDE
3072 }
3073
3074 sp<IBinder> token = target.inputChannel->getConnectionToken();
3075 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003076 if (connection == nullptr) {
3077 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003078 }
3079 newConnectionTokens.insert(std::move(token));
3080 newConnections.emplace_back(connection);
3081 }
3082 if (newConnectionTokens == mInteractionConnectionTokens) {
3083 return; // no change
3084 }
3085 mInteractionConnectionTokens = newConnectionTokens;
3086
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003087 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003088 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003089 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003090 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003091 std::string message = "Interaction with: " + targetList;
3092 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003093 message += "<none>";
3094 }
3095 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3096}
3097
chaviwfd6d3512019-03-25 13:23:49 -07003098void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003099 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003100 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003101 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3102 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003103 return;
3104 }
3105
Vishnu Nairc519ff72021-01-21 08:23:08 -08003106 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003107 if (focusedToken == token) {
3108 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003109 return;
3110 }
3111
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003112 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3113 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003114 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003115 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116}
3117
3118void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003120 if (ATRACE_ENABLED()) {
3121 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003123 ATRACE_NAME(message.c_str());
3124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127#endif
3128
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003129 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3130 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003132 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003133 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003134 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135
3136 // Publish the event.
3137 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003138 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3139 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003140 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3142 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003145 status = connection->inputPublisher
3146 .publishKeyEvent(dispatchEntry->seq,
3147 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3148 keyEntry.source, keyEntry.displayId,
3149 std::move(hmac), dispatchEntry->resolvedAction,
3150 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3151 keyEntry.scanCode, keyEntry.metaState,
3152 keyEntry.repeatCount, keyEntry.downTime,
3153 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
3156
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003157 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162
chaviw82357092020-01-28 13:13:06 -08003163 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3166 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003167 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3169 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003170 // Don't apply window scale here since we don't want scale to affect raw
3171 // coordinates. The scale will be sent back to the client and applied
3172 // later when requesting relative coordinates.
3173 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3174 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 }
3176 usingCoords = scaledCoords;
3177 }
3178 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 // We don't want the dispatch target to know.
3180 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 scaledCoords[i].clear();
3183 }
3184 usingCoords = scaledCoords;
3185 }
3186 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189
3190 // Publish the motion event.
3191 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003192 .publishMotionEvent(dispatchEntry->seq,
3193 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003194 motionEntry.deviceId, motionEntry.source,
3195 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003196 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003197 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003199 motionEntry.edgeFlags, motionEntry.metaState,
3200 motionEntry.buttonState,
3201 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003202 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003203 motionEntry.xPrecision, motionEntry.yPrecision,
3204 motionEntry.xCursorPosition,
3205 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003206 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003207 dispatchEntry->displaySize.x,
3208 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003209 motionEntry.downTime, motionEntry.eventTime,
3210 motionEntry.pointerCount,
3211 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 break;
3213 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003214
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003215 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003216 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003217 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003218 focusEntry.id,
3219 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003220 mInTouchMode);
3221 break;
3222 }
3223
Prabir Pradhan99987712020-11-10 18:43:05 -08003224 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3225 const auto& captureEntry =
3226 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3227 status = connection->inputPublisher
3228 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhanac483a62021-08-06 14:01:18 +00003229 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003230 break;
3231 }
3232
arthurhungb89ccb02020-12-30 16:19:01 +08003233 case EventEntry::Type::DRAG: {
3234 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3235 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3236 dragEntry.id, dragEntry.x,
3237 dragEntry.y,
3238 dragEntry.isExiting);
3239 break;
3240 }
3241
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003242 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003243 case EventEntry::Type::DEVICE_RESET:
3244 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003245 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003246 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250
3251 // Check the result.
3252 if (status) {
3253 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003254 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 "This is unexpected because the wait queue is empty, so the pipe "
3257 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003258 "event to it, status=%s(%d)",
3259 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3260 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3262 } else {
3263 // Pipe is full and we are waiting for the app to finish process some events
3264 // before sending more events to it.
3265#if DEBUG_DISPATCH_CYCLE
3266 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 "waiting for the application to catch up",
3268 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 }
3271 } else {
3272 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003273 "status=%s(%d)",
3274 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3275 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3277 }
3278 return;
3279 }
3280
3281 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003282 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3283 connection->outboundQueue.end(),
3284 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003285 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003286 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003287 if (connection->responsive) {
3288 mAnrTracker.insert(dispatchEntry->timeoutTime,
3289 connection->inputChannel->getConnectionToken());
3290 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003291 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292 }
3293}
3294
chaviw09c8d2d2020-08-24 15:48:26 -07003295std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3296 size_t size;
3297 switch (event.type) {
3298 case VerifiedInputEvent::Type::KEY: {
3299 size = sizeof(VerifiedKeyEvent);
3300 break;
3301 }
3302 case VerifiedInputEvent::Type::MOTION: {
3303 size = sizeof(VerifiedMotionEvent);
3304 break;
3305 }
3306 }
3307 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3308 return mHmacKeyManager.sign(start, size);
3309}
3310
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003311const std::array<uint8_t, 32> InputDispatcher::getSignature(
3312 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3313 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3314 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3315 // Only sign events up and down events as the purely move events
3316 // are tied to their up/down counterparts so signing would be redundant.
3317 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3318 verifiedEvent.actionMasked = actionMasked;
3319 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003320 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003321 }
3322 return INVALID_HMAC;
3323}
3324
3325const std::array<uint8_t, 32> InputDispatcher::getSignature(
3326 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3327 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3328 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3329 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003330 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003331}
3332
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003335 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336#if DEBUG_DISPATCH_CYCLE
3337 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339#endif
3340
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 if (connection->status == Connection::STATUS_BROKEN ||
3342 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 return;
3344 }
3345
3346 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003347 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348}
3349
3350void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 const sp<Connection>& connection,
3352 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353#if DEBUG_DISPATCH_CYCLE
3354 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356#endif
3357
3358 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003359 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003360 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003361 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003362 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363
3364 // The connection appears to be unrecoverably broken.
3365 // Ignore already broken or zombie connections.
3366 if (connection->status == Connection::STATUS_NORMAL) {
3367 connection->status = Connection::STATUS_BROKEN;
3368
3369 if (notify) {
3370 // Notify other system components.
3371 onDispatchCycleBrokenLocked(currentTime, connection);
3372 }
3373 }
3374}
3375
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003376void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3377 while (!queue.empty()) {
3378 DispatchEntry* dispatchEntry = queue.front();
3379 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003380 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
3382}
3383
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003384void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003386 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
3388 delete dispatchEntry;
3389}
3390
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003391int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3392 std::scoped_lock _l(mLock);
3393 sp<Connection> connection = getConnectionLocked(connectionToken);
3394 if (connection == nullptr) {
3395 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3396 connectionToken.get(), events);
3397 return 0; // remove the callback
3398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003400 bool notify;
3401 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3402 if (!(events & ALOOPER_EVENT_INPUT)) {
3403 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3404 "events=0x%x",
3405 connection->getInputChannelName().c_str(), events);
3406 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
3408
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003409 nsecs_t currentTime = now();
3410 bool gotOne = false;
3411 status_t status = OK;
3412 for (;;) {
3413 Result<InputPublisher::ConsumerResponse> result =
3414 connection->inputPublisher.receiveConsumerResponse();
3415 if (!result.ok()) {
3416 status = result.error().code();
3417 break;
3418 }
3419
3420 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3421 const InputPublisher::Finished& finish =
3422 std::get<InputPublisher::Finished>(*result);
3423 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3424 finish.consumeTime);
3425 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003426 if (shouldReportMetricsForConnection(*connection)) {
3427 const InputPublisher::Timeline& timeline =
3428 std::get<InputPublisher::Timeline>(*result);
3429 mLatencyTracker
3430 .trackGraphicsLatency(timeline.inputEventId,
3431 connection->inputChannel->getConnectionToken(),
3432 std::move(timeline.graphicsTimeline));
3433 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003434 }
3435 gotOne = true;
3436 }
3437 if (gotOne) {
3438 runCommandsLockedInterruptible();
3439 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 return 1;
3441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
3443
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003444 notify = status != DEAD_OBJECT || !connection->monitor;
3445 if (notify) {
3446 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3447 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3448 status);
3449 }
3450 } else {
3451 // Monitor channels are never explicitly unregistered.
3452 // We do it automatically when the remote endpoint is closed so don't warn about them.
3453 const bool stillHaveWindowHandle =
3454 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3455 notify = !connection->monitor && stillHaveWindowHandle;
3456 if (notify) {
3457 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3458 connection->getInputChannelName().c_str(), events);
3459 }
3460 }
3461
3462 // Remove the channel.
3463 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3464 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465}
3466
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003469 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003470 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472}
3473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003474void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003475 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003476 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3477 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3478}
3479
3480void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3481 const CancelationOptions& options,
3482 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3483 for (const auto& it : monitorsByDisplay) {
3484 const std::vector<Monitor>& monitors = it.second;
3485 for (const Monitor& monitor : monitors) {
3486 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003487 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003488 }
3489}
3490
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003492 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003493 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003494 if (connection == nullptr) {
3495 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003497
3498 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499}
3500
3501void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3502 const sp<Connection>& connection, const CancelationOptions& options) {
3503 if (connection->status == Connection::STATUS_BROKEN) {
3504 return;
3505 }
3506
3507 nsecs_t currentTime = now();
3508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003509 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003510 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003512 if (cancelationEvents.empty()) {
3513 return;
3514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003516 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3517 "with reality: %s, mode=%d.",
3518 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3519 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003521
3522 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003523 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003524 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3525 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003526 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003527 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003528 target.globalScaleFactor = windowInfo->globalScaleFactor;
3529 }
3530 target.inputChannel = connection->inputChannel;
3531 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3532
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003533 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003534 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003535 switch (cancelationEventEntry->type) {
3536 case EventEntry::Type::KEY: {
3537 logOutboundKeyDetails("cancel - ",
3538 static_cast<const KeyEntry&>(*cancelationEventEntry));
3539 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003541 case EventEntry::Type::MOTION: {
3542 logOutboundMotionDetails("cancel - ",
3543 static_cast<const MotionEntry&>(*cancelationEventEntry));
3544 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003546 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003547 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3548 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003549 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003550 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003551 break;
3552 }
3553 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003554 case EventEntry::Type::DEVICE_RESET:
3555 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003556 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003557 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003558 break;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003562 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3563 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003565
3566 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567}
3568
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3570 const sp<Connection>& connection) {
3571 if (connection->status == Connection::STATUS_BROKEN) {
3572 return;
3573 }
3574
3575 nsecs_t currentTime = now();
3576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003577 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003578 connection->inputState.synthesizePointerDownEvents(currentTime);
3579
3580 if (downEvents.empty()) {
3581 return;
3582 }
3583
3584#if DEBUG_OUTBOUND_EVENT_DETAILS
3585 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3586 connection->getInputChannelName().c_str(), downEvents.size());
3587#endif
3588
3589 InputTarget target;
chaviw3277faf2021-05-19 16:45:23 -05003590 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003591 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3592 if (windowHandle != nullptr) {
chaviw3277faf2021-05-19 16:45:23 -05003593 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003594 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003595 target.globalScaleFactor = windowInfo->globalScaleFactor;
3596 }
3597 target.inputChannel = connection->inputChannel;
3598 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003600 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003601 switch (downEventEntry->type) {
3602 case EventEntry::Type::MOTION: {
3603 logOutboundMotionDetails("down - ",
3604 static_cast<const MotionEntry&>(*downEventEntry));
3605 break;
3606 }
3607
3608 case EventEntry::Type::KEY:
3609 case EventEntry::Type::FOCUS:
3610 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003611 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003612 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003613 case EventEntry::Type::SENSOR:
3614 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003615 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003616 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003617 break;
3618 }
3619 }
3620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003621 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3622 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 }
3624
3625 startDispatchCycleLocked(currentTime, connection);
3626}
3627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3629 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 ALOG_ASSERT(pointerIds.value != 0);
3631
3632 uint32_t splitPointerIndexMap[MAX_POINTERS];
3633 PointerProperties splitPointerProperties[MAX_POINTERS];
3634 PointerCoords splitPointerCoords[MAX_POINTERS];
3635
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003636 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 uint32_t splitPointerCount = 0;
3638
3639 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003640 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003642 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 uint32_t pointerId = uint32_t(pointerProperties.id);
3644 if (pointerIds.hasBit(pointerId)) {
3645 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3646 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3647 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003648 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 splitPointerCount += 1;
3650 }
3651 }
3652
3653 if (splitPointerCount != pointerIds.count()) {
3654 // This is bad. We are missing some of the pointers that we expected to deliver.
3655 // Most likely this indicates that we received an ACTION_MOVE events that has
3656 // different pointer ids than we expected based on the previous ACTION_DOWN
3657 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3658 // in this way.
3659 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 "we expected there to be %d pointers. This probably means we received "
3661 "a broken sequence of pointer ids from the input device.",
3662 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003663 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003666 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3669 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3671 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003672 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 uint32_t pointerId = uint32_t(pointerProperties.id);
3674 if (pointerIds.hasBit(pointerId)) {
3675 if (pointerIds.count() == 1) {
3676 // The first/last pointer went down/up.
3677 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003678 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003679 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3680 ? AMOTION_EVENT_ACTION_CANCEL
3681 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 } else {
3683 // A secondary pointer went down/up.
3684 uint32_t splitPointerIndex = 0;
3685 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3686 splitPointerIndex += 1;
3687 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003688 action = maskedAction |
3689 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691 } else {
3692 // An unrelated pointer changed.
3693 action = AMOTION_EVENT_ACTION_MOVE;
3694 }
3695 }
3696
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003697 int32_t newId = mIdGenerator.nextId();
3698 if (ATRACE_ENABLED()) {
3699 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3700 ") to MotionEvent(id=0x%" PRIx32 ").",
3701 originalMotionEntry.id, newId);
3702 ATRACE_NAME(message.c_str());
3703 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 std::unique_ptr<MotionEntry> splitMotionEntry =
3705 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3706 originalMotionEntry.deviceId, originalMotionEntry.source,
3707 originalMotionEntry.displayId,
3708 originalMotionEntry.policyFlags, action,
3709 originalMotionEntry.actionButton,
3710 originalMotionEntry.flags, originalMotionEntry.metaState,
3711 originalMotionEntry.buttonState,
3712 originalMotionEntry.classification,
3713 originalMotionEntry.edgeFlags,
3714 originalMotionEntry.xPrecision,
3715 originalMotionEntry.yPrecision,
3716 originalMotionEntry.xCursorPosition,
3717 originalMotionEntry.yCursorPosition,
3718 originalMotionEntry.downTime, splitPointerCount,
3719 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003721 if (originalMotionEntry.injectionState) {
3722 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 splitMotionEntry->injectionState->refCount += 1;
3724 }
3725
3726 return splitMotionEntry;
3727}
3728
3729void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3730#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003731 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732#endif
3733
3734 bool needWake;
3735 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003736 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003738 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3739 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3740 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 } // release lock
3742
3743 if (needWake) {
3744 mLooper->wake();
3745 }
3746}
3747
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003748/**
3749 * If one of the meta shortcuts is detected, process them here:
3750 * Meta + Backspace -> generate BACK
3751 * Meta + Enter -> generate HOME
3752 * This will potentially overwrite keyCode and metaState.
3753 */
3754void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003755 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003756 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3757 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3758 if (keyCode == AKEYCODE_DEL) {
3759 newKeyCode = AKEYCODE_BACK;
3760 } else if (keyCode == AKEYCODE_ENTER) {
3761 newKeyCode = AKEYCODE_HOME;
3762 }
3763 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003764 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003765 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003766 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003767 keyCode = newKeyCode;
3768 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3769 }
3770 } else if (action == AKEY_EVENT_ACTION_UP) {
3771 // In order to maintain a consistent stream of up and down events, check to see if the key
3772 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3773 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003774 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003775 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003776 auto replacementIt = mReplacedKeys.find(replacement);
3777 if (replacementIt != mReplacedKeys.end()) {
3778 keyCode = replacementIt->second;
3779 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003780 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3781 }
3782 }
3783}
3784
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3786#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3788 "policyFlags=0x%x, action=0x%x, "
3789 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3790 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3791 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3792 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793#endif
3794 if (!validateKeyEvent(args->action)) {
3795 return;
3796 }
3797
3798 uint32_t policyFlags = args->policyFlags;
3799 int32_t flags = args->flags;
3800 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003801 // InputDispatcher tracks and generates key repeats on behalf of
3802 // whatever notifies it, so repeatCount should always be set to 0
3803 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3805 policyFlags |= POLICY_FLAG_VIRTUAL;
3806 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 if (policyFlags & POLICY_FLAG_FUNCTION) {
3809 metaState |= AMETA_FUNCTION_ON;
3810 }
3811
3812 policyFlags |= POLICY_FLAG_TRUSTED;
3813
Michael Wright78f24442014-08-06 15:55:28 -07003814 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003815 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003816
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003818 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003819 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3820 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
Michael Wright2b3c3302018-03-02 17:19:13 +00003822 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003824 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3825 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 bool needWake;
3830 { // acquire lock
3831 mLock.lock();
3832
3833 if (shouldSendKeyToInputFilterLocked(args)) {
3834 mLock.unlock();
3835
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003836 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3838 return; // event was consumed by the filter
3839 }
3840
3841 mLock.lock();
3842 }
3843
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003844 std::unique_ptr<KeyEntry> newEntry =
3845 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3846 args->displayId, policyFlags, args->action, flags,
3847 keyCode, args->scanCode, metaState, repeatCount,
3848 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003850 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 mLock.unlock();
3852 } // release lock
3853
3854 if (needWake) {
3855 mLooper->wake();
3856 }
3857}
3858
3859bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3860 return mInputFilterEnabled;
3861}
3862
3863void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3864#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003865 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3866 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003867 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3868 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003869 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003870 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3871 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3872 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3873 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 for (uint32_t i = 0; i < args->pointerCount; i++) {
3875 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003876 "x=%f, y=%f, pressure=%f, size=%f, "
3877 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3878 "orientation=%f",
3879 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3880 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3881 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3882 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3883 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3884 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3885 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3886 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3887 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3888 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 }
3890#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003891 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3892 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 return;
3894 }
3895
3896 uint32_t policyFlags = args->policyFlags;
3897 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003898
3899 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003900 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003901 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3902 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
3906 bool needWake;
3907 { // acquire lock
3908 mLock.lock();
3909
3910 if (shouldSendMotionToInputFilterLocked(args)) {
3911 mLock.unlock();
3912
3913 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003914 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003915 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3916 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003917 args->metaState, args->buttonState, args->classification, transform,
3918 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003919 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3920 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3921 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922
3923 policyFlags |= POLICY_FLAG_FILTERED;
3924 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3925 return; // event was consumed by the filter
3926 }
3927
3928 mLock.lock();
3929 }
3930
3931 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003932 std::unique_ptr<MotionEntry> newEntry =
3933 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3934 args->source, args->displayId, policyFlags,
3935 args->action, args->actionButton, args->flags,
3936 args->metaState, args->buttonState,
3937 args->classification, args->edgeFlags,
3938 args->xPrecision, args->yPrecision,
3939 args->xCursorPosition, args->yCursorPosition,
3940 args->downTime, args->pointerCount,
3941 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003943 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 mLock.unlock();
3945 } // release lock
3946
3947 if (needWake) {
3948 mLooper->wake();
3949 }
3950}
3951
Chris Yef59a2f42020-10-16 12:55:26 -07003952void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3953#if DEBUG_INBOUND_EVENT_DETAILS
3954 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3955 " sensorType=%s",
3956 args->id, args->eventTime, args->deviceId, args->source,
3957 NamedEnum::string(args->sensorType).c_str());
3958#endif
3959
3960 bool needWake;
3961 { // acquire lock
3962 mLock.lock();
3963
3964 // Just enqueue a new sensor event.
3965 std::unique_ptr<SensorEntry> newEntry =
3966 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3967 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3968 args->sensorType, args->accuracy,
3969 args->accuracyChanged, args->values);
3970
3971 needWake = enqueueInboundEventLocked(std::move(newEntry));
3972 mLock.unlock();
3973 } // release lock
3974
3975 if (needWake) {
3976 mLooper->wake();
3977 }
3978}
3979
Chris Yefb552902021-02-03 17:18:37 -08003980void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3981#if DEBUG_INBOUND_EVENT_DETAILS
3982 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3983 args->deviceId, args->isOn);
3984#endif
3985 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3986}
3987
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003989 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990}
3991
3992void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3993#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003994 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003995 "switchMask=0x%08x",
3996 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997#endif
3998
3999 uint32_t policyFlags = args->policyFlags;
4000 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002}
4003
4004void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
4005#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4007 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008#endif
4009
4010 bool needWake;
4011 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004012 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 std::unique_ptr<DeviceResetEntry> newEntry =
4015 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4016 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 } // release lock
4018
4019 if (needWake) {
4020 mLooper->wake();
4021 }
4022}
4023
Prabir Pradhan7e186182020-11-10 13:56:45 -08004024void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
4025#if DEBUG_INBOUND_EVENT_DETAILS
4026 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhanac483a62021-08-06 14:01:18 +00004027 args->request.enable ? "true" : "false");
Prabir Pradhan7e186182020-11-10 13:56:45 -08004028#endif
4029
Prabir Pradhan99987712020-11-10 18:43:05 -08004030 bool needWake;
4031 { // acquire lock
4032 std::scoped_lock _l(mLock);
4033 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhanac483a62021-08-06 14:01:18 +00004034 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004035 needWake = enqueueInboundEventLocked(std::move(entry));
4036 } // release lock
4037
4038 if (needWake) {
4039 mLooper->wake();
4040 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004041}
4042
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004043InputEventInjectionResult InputDispatcher::injectInputEvent(
4044 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4045 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046#if DEBUG_INBOUND_EVENT_DETAILS
4047 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004048 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4049 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004051 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
4053 policyFlags |= POLICY_FLAG_INJECTED;
4054 if (hasInjectionPermission(injectorPid, injectorUid)) {
4055 policyFlags |= POLICY_FLAG_TRUSTED;
4056 }
4057
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004058 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004059 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4060 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4061 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4062 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4063 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004064 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004065 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004066 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004067 }
4068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004072 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4073 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004075 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004078 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004079 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4080 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4081 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004082 int32_t keyCode = incomingKey.getKeyCode();
4083 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004084 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004086 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004087 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004088 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4089 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4090 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4093 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004094 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095
4096 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4097 android::base::Timer t;
4098 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4099 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4100 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4101 std::to_string(t.duration().count()).c_str());
4102 }
4103 }
4104
4105 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004106 std::unique_ptr<KeyEntry> injectedEntry =
4107 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004108 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004109 incomingKey.getDisplayId(), policyFlags, action,
4110 flags, keyCode, incomingKey.getScanCode(), metaState,
4111 incomingKey.getRepeatCount(),
4112 incomingKey.getDownTime());
4113 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004114 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 }
4116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004117 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4119 int32_t action = motionEvent.getAction();
4120 size_t pointerCount = motionEvent.getPointerCount();
4121 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4122 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004123 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004124 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004126 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 }
4128
4129 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 android::base::Timer t;
4132 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4133 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4134 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4135 std::to_string(t.duration().count()).c_str());
4136 }
4137 }
4138
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004139 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4140 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4141 }
4142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004144 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4145 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004147 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4148 resolvedDeviceId, motionEvent.getSource(),
4149 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004150 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004151 motionEvent.getButtonState(),
4152 motionEvent.getClassification(),
4153 motionEvent.getEdgeFlags(),
4154 motionEvent.getXPrecision(),
4155 motionEvent.getYPrecision(),
4156 motionEvent.getRawXCursorPosition(),
4157 motionEvent.getRawYCursorPosition(),
4158 motionEvent.getDownTime(), uint32_t(pointerCount),
4159 pointerProperties, samplePointerCoords,
4160 motionEvent.getXOffset(),
4161 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004163 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164 sampleEventTimes += 1;
4165 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004166 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004167 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4168 resolvedDeviceId, motionEvent.getSource(),
4169 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004170 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004171 motionEvent.getMetaState(),
4172 motionEvent.getButtonState(),
4173 motionEvent.getClassification(),
4174 motionEvent.getEdgeFlags(),
4175 motionEvent.getXPrecision(),
4176 motionEvent.getYPrecision(),
4177 motionEvent.getRawXCursorPosition(),
4178 motionEvent.getRawYCursorPosition(),
4179 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004180 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004181 samplePointerCoords, motionEvent.getXOffset(),
4182 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004183 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 }
4185 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004189 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004190 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 }
4192
4193 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004194 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 injectionState->injectionIsAsync = true;
4196 }
4197
4198 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004199 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
4201 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004202 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004203 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004204 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 }
4206
4207 mLock.unlock();
4208
4209 if (needWake) {
4210 mLooper->wake();
4211 }
4212
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004213 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004215 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004217 if (syncMode == InputEventInjectionSync::NONE) {
4218 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 } else {
4220 for (;;) {
4221 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004222 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 }
4225
4226 nsecs_t remainingTimeout = endTime - now();
4227 if (remainingTimeout <= 0) {
4228#if DEBUG_INJECTION
4229 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004232 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 break;
4234 }
4235
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004236 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 }
4238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004239 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4240 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 while (injectionState->pendingForegroundDispatches != 0) {
4242#if DEBUG_INJECTION
4243 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245#endif
4246 nsecs_t remainingTimeout = endTime - now();
4247 if (remainingTimeout <= 0) {
4248#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4250 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004252 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 break;
4254 }
4255
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004256 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 }
4258 }
4259 }
4260
4261 injectionState->release();
4262 } // release lock
4263
4264#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004265 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004266 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267#endif
4268
4269 return injectionResult;
4270}
4271
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004272std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004273 std::array<uint8_t, 32> calculatedHmac;
4274 std::unique_ptr<VerifiedInputEvent> result;
4275 switch (event.getType()) {
4276 case AINPUT_EVENT_TYPE_KEY: {
4277 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4278 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4279 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004280 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004281 break;
4282 }
4283 case AINPUT_EVENT_TYPE_MOTION: {
4284 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4285 VerifiedMotionEvent verifiedMotionEvent =
4286 verifiedMotionEventFromMotionEvent(motionEvent);
4287 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004288 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004289 break;
4290 }
4291 default: {
4292 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4293 return nullptr;
4294 }
4295 }
4296 if (calculatedHmac == INVALID_HMAC) {
4297 return nullptr;
4298 }
4299 if (calculatedHmac != event.getHmac()) {
4300 return nullptr;
4301 }
4302 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004303}
4304
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 return injectorUid == 0 ||
4307 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308}
4309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004312 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 if (injectionState) {
4314#if DEBUG_INJECTION
4315 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004316 "injectorPid=%d, injectorUid=%d",
4317 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318#endif
4319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 // Log the outcome since the injector did not wait for the injection result.
4322 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 ALOGV("Asynchronous input event injection succeeded.");
4325 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 ALOGW("Asynchronous input event injection failed.");
4328 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 ALOGW("Asynchronous input event injection permission denied.");
4331 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004332 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 ALOGW("Asynchronous input event injection timed out.");
4334 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004335 case InputEventInjectionResult::PENDING:
4336 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339 }
4340
4341 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004342 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344}
4345
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004346void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4347 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 if (injectionState) {
4349 injectionState->pendingForegroundDispatches += 1;
4350 }
4351}
4352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4354 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 if (injectionState) {
4356 injectionState->pendingForegroundDispatches -= 1;
4357
4358 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004359 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361 }
4362}
4363
chaviw3277faf2021-05-19 16:45:23 -05004364const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004365 int32_t displayId) const {
chaviw3277faf2021-05-19 16:45:23 -05004366 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004367 auto it = mWindowHandlesByDisplay.find(displayId);
4368 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004369}
4370
chaviw3277faf2021-05-19 16:45:23 -05004371sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004372 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004373 if (windowHandleToken == nullptr) {
4374 return nullptr;
4375 }
4376
Arthur Hungb92218b2018-08-14 12:00:21 +08004377 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004378 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4379 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004380 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004381 return windowHandle;
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 }
4384 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004385 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386}
4387
chaviw3277faf2021-05-19 16:45:23 -05004388sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4389 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004390 if (windowHandleToken == nullptr) {
4391 return nullptr;
4392 }
4393
chaviw3277faf2021-05-19 16:45:23 -05004394 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004395 if (windowHandle->getToken() == windowHandleToken) {
4396 return windowHandle;
4397 }
4398 }
4399 return nullptr;
4400}
4401
chaviw3277faf2021-05-19 16:45:23 -05004402sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4403 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004404 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05004405 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4406 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004407 if (handle->getId() == windowHandle->getId() &&
4408 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004409 if (windowHandle->getInfo()->displayId != it.first) {
4410 ALOGE("Found window %s in display %" PRId32
4411 ", but it should belong to display %" PRId32,
4412 windowHandle->getName().c_str(), it.first,
4413 windowHandle->getInfo()->displayId);
4414 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004415 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004419 return nullptr;
4420}
4421
chaviw3277faf2021-05-19 16:45:23 -05004422sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004423 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4424 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425}
4426
chaviw3277faf2021-05-19 16:45:23 -05004427bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004428 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4429 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004430 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004431 if (connection != nullptr && noInputChannel) {
4432 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4433 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4434 return false;
4435 }
4436
4437 if (connection == nullptr) {
4438 if (!noInputChannel) {
4439 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4440 }
4441 return false;
4442 }
4443 if (!connection->responsive) {
4444 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4445 return false;
4446 }
4447 return true;
4448}
4449
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004450std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4451 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004452 auto connectionIt = mConnectionsByToken.find(token);
4453 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004454 return nullptr;
4455 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004456 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004457}
4458
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004459void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw3277faf2021-05-19 16:45:23 -05004460 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4461 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004462 // Remove all handles on a display if there are no windows left.
4463 mWindowHandlesByDisplay.erase(displayId);
4464 return;
4465 }
4466
4467 // Since we compare the pointer of input window handles across window updates, we need
4468 // to make sure the handle object for the same window stays unchanged across updates.
chaviw3277faf2021-05-19 16:45:23 -05004469 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4470 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4471 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004472 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004473 }
4474
chaviw3277faf2021-05-19 16:45:23 -05004475 std::vector<sp<WindowInfoHandle>> newHandles;
4476 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw3277faf2021-05-19 16:45:23 -05004477 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004478 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4479 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4480 const bool noInputChannel =
chaviw3277faf2021-05-19 16:45:23 -05004481 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4482 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4483 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004484 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004485 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004486 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004487 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004488 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004489 }
4490
4491 if (info->displayId != displayId) {
4492 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4493 handle->getName().c_str(), displayId, info->displayId);
4494 continue;
4495 }
4496
Robert Carredd13602020-04-13 17:24:34 -07004497 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4498 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw3277faf2021-05-19 16:45:23 -05004499 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004500 oldHandle->updateFrom(handle);
4501 newHandles.push_back(oldHandle);
4502 } else {
4503 newHandles.push_back(handle);
4504 }
4505 }
4506
4507 // Insert or replace
4508 mWindowHandlesByDisplay[displayId] = newHandles;
4509}
4510
Arthur Hung72d8dc32020-03-28 00:48:39 +00004511void InputDispatcher::setInputWindows(
chaviw3277faf2021-05-19 16:45:23 -05004512 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004513 { // acquire lock
4514 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004515 for (const auto& [displayId, handles] : handlesPerDisplay) {
4516 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004517 }
4518 }
4519 // Wake up poll loop since it may need to make new input dispatching choices.
4520 mLooper->wake();
4521}
4522
Arthur Hungb92218b2018-08-14 12:00:21 +08004523/**
4524 * Called from InputManagerService, update window handle list by displayId that can receive input.
4525 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4526 * If set an empty list, remove all handles from the specific display.
4527 * For focused handle, check if need to change and send a cancel event to previous one.
4528 * For removed handle, check if need to send a cancel event if already in touch.
4529 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004530void InputDispatcher::setInputWindowsLocked(
chaviw3277faf2021-05-19 16:45:23 -05004531 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004532 if (DEBUG_FOCUS) {
4533 std::string windowList;
chaviw3277faf2021-05-19 16:45:23 -05004534 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004535 windowList += iwh->getName() + " ";
4536 }
4537 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004540 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw3277faf2021-05-19 16:45:23 -05004541 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004542 const bool noInputWindow =
chaviw3277faf2021-05-19 16:45:23 -05004543 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004544 if (noInputWindow && window->getToken() != nullptr) {
4545 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4546 window->getName().c_str());
4547 window->releaseChannel();
4548 }
4549 }
4550
Arthur Hung72d8dc32020-03-28 00:48:39 +00004551 // Copy old handles for release if they are no longer present.
chaviw3277faf2021-05-19 16:45:23 -05004552 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004554 // Save the old windows' orientation by ID before it gets updated.
4555 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw3277faf2021-05-19 16:45:23 -05004556 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004557 oldWindowOrientations.emplace(handle->getId(),
4558 handle->getInfo()->transform.getOrientation());
4559 }
4560
chaviw3277faf2021-05-19 16:45:23 -05004561 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004562
chaviw3277faf2021-05-19 16:45:23 -05004563 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004564 if (mLastHoverWindowHandle &&
4565 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4566 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004567 mLastHoverWindowHandle = nullptr;
4568 }
4569
Vishnu Nairc519ff72021-01-21 08:23:08 -08004570 std::optional<FocusResolver::FocusChanges> changes =
4571 mFocusResolver.setInputWindows(displayId, windowHandles);
4572 if (changes) {
4573 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004576 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4577 mTouchStatesByDisplay.find(displayId);
4578 if (stateIt != mTouchStatesByDisplay.end()) {
4579 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004580 for (size_t i = 0; i < state.windows.size();) {
4581 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004582 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004583 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004584 ALOGD("Touched window was removed: %s in display %" PRId32,
4585 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004586 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004587 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004588 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4589 if (touchedInputChannel != nullptr) {
4590 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4591 "touched window was removed");
4592 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004594 state.windows.erase(state.windows.begin() + i);
4595 } else {
4596 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 }
4598 }
arthurhungb89ccb02020-12-30 16:19:01 +08004599
arthurhung6d4bed92021-03-17 11:59:33 +08004600 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004601 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004602 if (mDragState &&
4603 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004604 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004605 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004606 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004607 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004608
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004609 if (isPerWindowInputRotationEnabled()) {
4610 // Determine if the orientation of any of the input windows have changed, and cancel all
4611 // pointer events if necessary.
chaviw3277faf2021-05-19 16:45:23 -05004612 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4613 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004614 if (newWindowHandle != nullptr &&
4615 newWindowHandle->getInfo()->transform.getOrientation() !=
4616 oldWindowOrientations[oldWindowHandle->getId()]) {
4617 std::shared_ptr<InputChannel> inputChannel =
4618 getInputChannelLocked(newWindowHandle->getToken());
4619 if (inputChannel != nullptr) {
4620 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4621 "touched window's orientation changed");
4622 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4623 }
4624 }
4625 }
4626 }
4627
Arthur Hung72d8dc32020-03-28 00:48:39 +00004628 // Release information for windows that are no longer present.
4629 // This ensures that unused input channels are released promptly.
4630 // Otherwise, they might stick around until the window handle is destroyed
4631 // which might not happen until the next GC.
chaviw3277faf2021-05-19 16:45:23 -05004632 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004633 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004634 if (DEBUG_FOCUS) {
4635 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004636 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004637 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004638 // To avoid making too many calls into the compat framework, only
4639 // check for window flags when windows are going away.
4640 // TODO(b/157929241) : delete this. This is only needed temporarily
4641 // in order to gather some data about the flag usage
chaviw3277faf2021-05-19 16:45:23 -05004642 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004643 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4644 oldWindowHandle->getName().c_str());
4645 if (mCompatService != nullptr) {
4646 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4647 oldWindowHandle->getInfo()->ownerUid);
4648 }
4649 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004650 }
chaviw291d88a2019-02-14 10:33:58 -08004651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652}
4653
4654void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004655 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004656 if (DEBUG_FOCUS) {
4657 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4658 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4659 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004660 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004661 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004662 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 } // release lock
4664
4665 // Wake up poll loop since it may need to make new input dispatching choices.
4666 mLooper->wake();
4667}
4668
Vishnu Nair599f1412021-06-21 10:39:58 -07004669void InputDispatcher::setFocusedApplicationLocked(
4670 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4671 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4672 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4673
4674 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4675 return; // This application is already focused. No need to wake up or change anything.
4676 }
4677
4678 // Set the new application handle.
4679 if (inputApplicationHandle != nullptr) {
4680 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4681 } else {
4682 mFocusedApplicationHandlesByDisplay.erase(displayId);
4683 }
4684
4685 // No matter what the old focused application was, stop waiting on it because it is
4686 // no longer focused.
4687 resetNoFocusedWindowTimeoutLocked();
4688}
4689
Tiger Huang721e26f2018-07-24 22:26:19 +08004690/**
4691 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4692 * the display not specified.
4693 *
4694 * We track any unreleased events for each window. If a window loses the ability to receive the
4695 * released event, we will send a cancel event to it. So when the focused display is changed, we
4696 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4697 * display. The display-specified events won't be affected.
4698 */
4699void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004700 if (DEBUG_FOCUS) {
4701 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4702 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004703 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004704 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004705
4706 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004707 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004708 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004709 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004710 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004711 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004712 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 CancelationOptions
4714 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4715 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004716 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004717 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4718 }
4719 }
4720 mFocusedDisplayId = displayId;
4721
Chris Ye3c2d6f52020-08-09 10:39:48 -07004722 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004723 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004724 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004725
Vishnu Nairad321cd2020-08-20 16:40:21 -07004726 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004727 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004728 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004729 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004730 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004731 }
4732 }
4733 }
4734
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004735 if (DEBUG_FOCUS) {
4736 logDispatchStateLocked();
4737 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004738 } // release lock
4739
4740 // Wake up poll loop since it may need to make new input dispatching choices.
4741 mLooper->wake();
4742}
4743
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004745 if (DEBUG_FOCUS) {
4746 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748
4749 bool changed;
4750 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004751 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
4753 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4754 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757
4758 if (mDispatchEnabled && !enabled) {
4759 resetAndDropEverythingLocked("dispatcher is being disabled");
4760 }
4761
4762 mDispatchEnabled = enabled;
4763 mDispatchFrozen = frozen;
4764 changed = true;
4765 } else {
4766 changed = false;
4767 }
4768
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004769 if (DEBUG_FOCUS) {
4770 logDispatchStateLocked();
4771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 } // release lock
4773
4774 if (changed) {
4775 // Wake up poll loop since it may need to make new input dispatching choices.
4776 mLooper->wake();
4777 }
4778}
4779
4780void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004781 if (DEBUG_FOCUS) {
4782 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784
4785 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004786 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787
4788 if (mInputFilterEnabled == enabled) {
4789 return;
4790 }
4791
4792 mInputFilterEnabled = enabled;
4793 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4794 } // release lock
4795
4796 // Wake up poll loop since there might be work to do to drop everything.
4797 mLooper->wake();
4798}
4799
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004800void InputDispatcher::setInTouchMode(bool inTouchMode) {
4801 std::scoped_lock lock(mLock);
4802 mInTouchMode = inTouchMode;
4803}
4804
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004805void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4806 if (opacity < 0 || opacity > 1) {
4807 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4808 return;
4809 }
4810
4811 std::scoped_lock lock(mLock);
4812 mMaximumObscuringOpacityForTouch = opacity;
4813}
4814
4815void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4816 std::scoped_lock lock(mLock);
4817 mBlockUntrustedTouchesMode = mode;
4818}
4819
Arthur Hungabbb9d82021-09-01 14:52:30 +00004820std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4821 const sp<IBinder>& token) {
4822 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4823 for (TouchedWindow& w : state.windows) {
4824 if (w.windowHandle->getToken() == token) {
4825 return std::make_pair(&state, &w);
4826 }
4827 }
4828 }
4829 return std::make_pair(nullptr, nullptr);
4830}
4831
arthurhungb89ccb02020-12-30 16:19:01 +08004832bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4833 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004834 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004835 if (DEBUG_FOCUS) {
4836 ALOGD("Trivial transfer to same window.");
4837 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004838 return true;
4839 }
4840
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004842 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843
Arthur Hungabbb9d82021-09-01 14:52:30 +00004844 // Find the target touch state and touched window by fromToken.
4845 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4846 if (state == nullptr || touchedWindow == nullptr) {
4847 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 return false;
4849 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004850
4851 const int32_t displayId = state->displayId;
4852 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4853 if (toWindowHandle == nullptr) {
4854 ALOGW("Cannot transfer focus because to window not found.");
4855 return false;
4856 }
4857
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004858 if (DEBUG_FOCUS) {
4859 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004860 touchedWindow->windowHandle->getName().c_str(),
4861 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
Arthur Hungabbb9d82021-09-01 14:52:30 +00004864 // Erase old window.
4865 int32_t oldTargetFlags = touchedWindow->targetFlags;
4866 BitSet32 pointerIds = touchedWindow->pointerIds;
4867 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868
Arthur Hungabbb9d82021-09-01 14:52:30 +00004869 // Add new window.
4870 int32_t newTargetFlags = oldTargetFlags &
4871 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4872 InputTarget::FLAG_DISPATCH_AS_IS);
4873 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874
Arthur Hungabbb9d82021-09-01 14:52:30 +00004875 // Store the dragging window.
4876 if (isDragDrop) {
4877 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879
Arthur Hungabbb9d82021-09-01 14:52:30 +00004880 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004881 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4882 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004883 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004884 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004885 CancelationOptions
4886 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4887 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004889 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 }
4891
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004892 if (DEBUG_FOCUS) {
4893 logDispatchStateLocked();
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 } // release lock
4896
4897 // Wake up poll loop since it may need to make new input dispatching choices.
4898 mLooper->wake();
4899 return true;
4900}
4901
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004902// Binder call
4903bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4904 sp<IBinder> fromToken;
4905 { // acquire lock
4906 std::scoped_lock _l(mLock);
4907
Arthur Hungabbb9d82021-09-01 14:52:30 +00004908 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4909 [](const auto& pair) { return pair.second.windows.size() == 1; });
4910 if (it == mTouchStatesByDisplay.end()) {
4911 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4912 return false;
4913 }
4914 const int32_t displayId = it->first;
4915 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004916 if (toWindowHandle == nullptr) {
4917 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4918 return false;
4919 }
4920
Arthur Hungabbb9d82021-09-01 14:52:30 +00004921 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004922 const TouchedWindow& touchedWindow = state.windows[0];
4923 fromToken = touchedWindow.windowHandle->getToken();
4924 } // release lock
4925
4926 return transferTouchFocus(fromToken, destChannelToken);
4927}
4928
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004930 if (DEBUG_FOCUS) {
4931 ALOGD("Resetting and dropping all events (%s).", reason);
4932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
4934 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4935 synthesizeCancelationEventsForAllConnectionsLocked(options);
4936
4937 resetKeyRepeatLocked();
4938 releasePendingEventLocked();
4939 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004940 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004942 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004943 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004945 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946}
4947
4948void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 dumpDispatchStateLocked(dump);
4951
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004952 std::istringstream stream(dump);
4953 std::string line;
4954
4955 while (std::getline(stream, line, '\n')) {
4956 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 }
4958}
4959
Prabir Pradhan99987712020-11-10 18:43:05 -08004960std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4961 std::string dump;
4962
Prabir Pradhanac483a62021-08-06 14:01:18 +00004963 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4964 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08004965
4966 std::string windowName = "None";
4967 if (mWindowTokenWithPointerCapture) {
chaviw3277faf2021-05-19 16:45:23 -05004968 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004969 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4970 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4971 : "token has capture without window";
4972 }
Prabir Pradhanac483a62021-08-06 14:01:18 +00004973 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08004974
4975 return dump;
4976}
4977
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004978void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004979 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4980 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4981 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004982 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
Tiger Huang721e26f2018-07-24 22:26:19 +08004984 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4985 dump += StringPrintf(INDENT "FocusedApplications:\n");
4986 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4987 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004988 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004989 const std::chrono::duration timeout =
4990 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004991 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004992 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004993 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004996 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004998
Vishnu Nairc519ff72021-01-21 08:23:08 -08004999 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005000 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005002 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005003 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005004 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5005 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005006 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 state.displayId, toString(state.down), toString(state.split),
5008 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005009 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005010 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005011 for (size_t i = 0; i < state.windows.size(); i++) {
5012 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005013 dump += StringPrintf(INDENT4
5014 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5015 i, touchedWindow.windowHandle->getName().c_str(),
5016 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005017 }
5018 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005019 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005020 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005021 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005022 dump += INDENT3 "Portal windows:\n";
5023 for (size_t i = 0; i < state.portalWindows.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005024 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005025 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5026 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005027 }
5028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 }
5030 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005031 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032 }
5033
arthurhung6d4bed92021-03-17 11:59:33 +08005034 if (mDragState) {
5035 dump += StringPrintf(INDENT "DragState:\n");
5036 mDragState->dump(dump, INDENT2);
5037 }
5038
Arthur Hungb92218b2018-08-14 12:00:21 +08005039 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005040 for (auto& it : mWindowHandlesByDisplay) {
chaviw3277faf2021-05-19 16:45:23 -05005041 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005042 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005043 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005044 dump += INDENT2 "Windows:\n";
5045 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw3277faf2021-05-19 16:45:23 -05005046 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5047 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005049 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07005050 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005051 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005052 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005053 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005054 "applicationInfo.name=%s, "
5055 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005056 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005057 i, windowInfo->name.c_str(), windowInfo->id,
5058 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005059 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005060 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005061 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005062 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005063 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005064 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005065 windowInfo->frameLeft, windowInfo->frameTop,
5066 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005067 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005068 windowInfo->applicationInfo.name.c_str(),
5069 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005070 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005071 dump += StringPrintf(", inputFeatures=%s",
5072 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005073 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005074 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005075 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005076 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005077 millis(windowInfo->dispatchingTimeout),
5078 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005079 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005080 toString(windowInfo->touchOcclusionMode).c_str(),
5081 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005082 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005083 }
5084 } else {
5085 dump += INDENT2 "Windows: <none>\n";
5086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005089 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 }
5091
Michael Wright3dd60e22019-03-27 22:06:44 +00005092 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005093 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005094 const std::vector<Monitor>& monitors = it.second;
5095 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5096 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005097 }
5098 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005099 const std::vector<Monitor>& monitors = it.second;
5100 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5101 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005104 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
5106
5107 nsecs_t currentTime = now();
5108
5109 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005110 if (!mRecentQueue.empty()) {
5111 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005112 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005113 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005114 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005115 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 }
5117 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005118 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
5120
5121 // Dump event currently being dispatched.
5122 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005123 dump += INDENT "PendingEvent:\n";
5124 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005125 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005126 dump += StringPrintf(", age=%" PRId64 "ms\n",
5127 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005129 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131
5132 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005133 if (!mInboundQueue.empty()) {
5134 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005135 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005136 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005137 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005138 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 }
5140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 }
5143
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005144 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005145 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005146 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5147 const KeyReplacement& replacement = pair.first;
5148 int32_t newKeyCode = pair.second;
5149 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005150 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005151 }
5152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005154 }
5155
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005156 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005157 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005158 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005159 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005160 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005161 connection->inputChannel->getFd().get(),
5162 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005163 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005164 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005166 if (!connection->outboundQueue.empty()) {
5167 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5168 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005169 dump += dumpQueue(connection->outboundQueue, currentTime);
5170
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005175 if (!connection->waitQueue.empty()) {
5176 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5177 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005178 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005180 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 }
5182 }
5183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186
5187 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005188 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5189 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005191 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
5193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005194 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005195 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5196 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5197 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005198 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005199 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200}
5201
Michael Wright3dd60e22019-03-27 22:06:44 +00005202void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5203 const size_t numMonitors = monitors.size();
5204 for (size_t i = 0; i < numMonitors; i++) {
5205 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005206 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005207 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5208 dump += "\n";
5209 }
5210}
5211
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005212class LooperEventCallback : public LooperCallback {
5213public:
5214 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5215 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5216
5217private:
5218 std::function<int(int events)> mCallback;
5219};
5220
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005221Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005222#if DEBUG_CHANNEL_CREATION
5223 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224#endif
5225
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005226 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005227 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005228 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005229
5230 if (result) {
5231 return base::Error(result) << "Failed to open input channel pair with name " << name;
5232 }
5233
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005235 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005236 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005237 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005238 sp<Connection> connection =
5239 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005241 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5242 ALOGE("Created a new connection, but the token %p is already known", token.get());
5243 }
5244 mConnectionsByToken.emplace(token, connection);
5245
5246 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5247 this, std::placeholders::_1, token);
5248
5249 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 } // release lock
5251
5252 // Wake the looper because some connections have changed.
5253 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005254 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255}
5256
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005257Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5258 bool isGestureMonitor,
5259 const std::string& name,
5260 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005261 std::shared_ptr<InputChannel> serverChannel;
5262 std::unique_ptr<InputChannel> clientChannel;
5263 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5264 if (result) {
5265 return base::Error(result) << "Failed to open input channel pair with name " << name;
5266 }
5267
Michael Wright3dd60e22019-03-27 22:06:44 +00005268 { // acquire lock
5269 std::scoped_lock _l(mLock);
5270
5271 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005272 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5273 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 }
5275
Garfield Tan15601662020-09-22 15:32:38 -07005276 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005277 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005278 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005279
5280 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5281 ALOGE("Created a new connection, but the token %p is already known", token.get());
5282 }
5283 mConnectionsByToken.emplace(token, connection);
5284 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5285 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287 auto& monitorsByDisplay =
5288 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005289 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005290
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005291 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005292 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5293 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005294 }
Garfield Tan15601662020-09-22 15:32:38 -07005295
Michael Wright3dd60e22019-03-27 22:06:44 +00005296 // Wake the looper because some connections have changed.
5297 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005298 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005299}
5300
Garfield Tan15601662020-09-22 15:32:38 -07005301status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005303 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304
Garfield Tan15601662020-09-22 15:32:38 -07005305 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306 if (status) {
5307 return status;
5308 }
5309 } // release lock
5310
5311 // Wake the poll loop because removing the connection may have changed the current
5312 // synchronization state.
5313 mLooper->wake();
5314 return OK;
5315}
5316
Garfield Tan15601662020-09-22 15:32:38 -07005317status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5318 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005319 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005320 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005321 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 return BAD_VALUE;
5323 }
5324
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005325 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005326
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005328 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005331 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
5333 nsecs_t currentTime = now();
5334 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5335
5336 connection->status = Connection::STATUS_ZOMBIE;
5337 return OK;
5338}
5339
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005340void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5341 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5342 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005343}
5344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005345void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005346 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005347 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005348 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005349 std::vector<Monitor>& monitors = it->second;
5350 const size_t numMonitors = monitors.size();
5351 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005352 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005353 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5354 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005355 monitors.erase(monitors.begin() + i);
5356 break;
5357 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005358 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005359 if (monitors.empty()) {
5360 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005361 } else {
5362 ++it;
5363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 }
5365}
5366
Michael Wright3dd60e22019-03-27 22:06:44 +00005367status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5368 { // acquire lock
5369 std::scoped_lock _l(mLock);
5370 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5371
5372 if (!foundDisplayId) {
5373 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5374 return BAD_VALUE;
5375 }
5376 int32_t displayId = foundDisplayId.value();
5377
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005378 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5379 mTouchStatesByDisplay.find(displayId);
5380 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005381 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5382 return BAD_VALUE;
5383 }
5384
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005385 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005386 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005387 std::optional<int32_t> foundDeviceId;
5388 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005389 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005390 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005391 foundDeviceId = state.deviceId;
5392 }
5393 }
5394 if (!foundDeviceId || !state.down) {
5395 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005396 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005397 return BAD_VALUE;
5398 }
5399 int32_t deviceId = foundDeviceId.value();
5400
5401 // Send cancel events to all the input channels we're stealing from.
5402 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005403 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005404 options.deviceId = deviceId;
5405 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005406 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005407 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005408 std::shared_ptr<InputChannel> channel =
5409 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005410 if (channel != nullptr) {
5411 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005412 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005413 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005414 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005415 canceledWindows += "]";
5416 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5417 canceledWindows.c_str());
5418
Michael Wright3dd60e22019-03-27 22:06:44 +00005419 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hung71625472021-11-16 02:45:54 +00005420 state.split = false;
Michael Wright3dd60e22019-03-27 22:06:44 +00005421 state.filterNonMonitors();
5422 }
5423 return OK;
5424}
5425
Prabir Pradhan99987712020-11-10 18:43:05 -08005426void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5427 { // acquire lock
5428 std::scoped_lock _l(mLock);
5429 if (DEBUG_FOCUS) {
chaviw3277faf2021-05-19 16:45:23 -05005430 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005431 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5432 windowHandle != nullptr ? windowHandle->getName().c_str()
5433 : "token without window");
5434 }
5435
Vishnu Nairc519ff72021-01-21 08:23:08 -08005436 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005437 if (focusedToken != windowToken) {
5438 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5439 enabled ? "enable" : "disable");
5440 return;
5441 }
5442
Prabir Pradhanac483a62021-08-06 14:01:18 +00005443 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005444 ALOGW("Ignoring request to %s Pointer Capture: "
5445 "window has %s requested pointer capture.",
5446 enabled ? "enable" : "disable", enabled ? "already" : "not");
5447 return;
5448 }
5449
Prabir Pradhan99987712020-11-10 18:43:05 -08005450 setPointerCaptureLocked(enabled);
5451 } // release lock
5452
5453 // Wake the thread to process command entries.
5454 mLooper->wake();
5455}
5456
Michael Wright3dd60e22019-03-27 22:06:44 +00005457std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5458 const sp<IBinder>& token) {
5459 for (const auto& it : mGestureMonitorsByDisplay) {
5460 const std::vector<Monitor>& monitors = it.second;
5461 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005462 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005463 return it.first;
5464 }
5465 }
5466 }
5467 return std::nullopt;
5468}
5469
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005470std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5471 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5472 if (gesturePid.has_value()) {
5473 return gesturePid;
5474 }
5475 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5476}
5477
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005478sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005479 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005480 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005481 }
5482
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005483 for (const auto& [token, connection] : mConnectionsByToken) {
5484 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005485 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
5487 }
Robert Carr4e670e52018-08-15 13:26:12 -07005488
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005489 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490}
5491
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005492std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5493 sp<Connection> connection = getConnectionLocked(connectionToken);
5494 if (connection == nullptr) {
5495 return "<nullptr>";
5496 }
5497 return connection->getInputChannelName();
5498}
5499
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005500void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005502 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005503}
5504
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005505void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5506 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005507 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5509 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510 commandEntry->connection = connection;
5511 commandEntry->eventTime = currentTime;
5512 commandEntry->seq = seq;
5513 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005514 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005515 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516}
5517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005518void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5519 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005521 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005523 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5524 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005526 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527}
5528
Vishnu Nairad321cd2020-08-20 16:40:21 -07005529void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5530 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005531 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5532 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005533 commandEntry->oldToken = oldToken;
5534 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005535 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005536}
5537
arthurhungf452d0b2021-01-06 00:19:52 +08005538void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5539 std::unique_ptr<CommandEntry> commandEntry =
5540 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5541 commandEntry->newToken = token;
5542 commandEntry->x = x;
5543 commandEntry->y = y;
5544 postCommandLocked(std::move(commandEntry));
5545}
5546
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5548 if (connection == nullptr) {
5549 LOG_ALWAYS_FATAL("Caller must check for nullness");
5550 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005551 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5552 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005553 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005554 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005555 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556 return;
5557 }
5558 /**
5559 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5560 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5561 * has changed. This could cause newer entries to time out before the already dispatched
5562 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5563 * processes the events linearly. So providing information about the oldest entry seems to be
5564 * most useful.
5565 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005566 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5568 std::string reason =
5569 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005570 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005571 ns2ms(currentWait),
5572 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005573 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005574 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005575
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005576 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5577
5578 // Stop waking up for events on this connection, it is already unresponsive
5579 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005580}
5581
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005582void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5583 std::string reason =
5584 StringPrintf("%s does not have a focused window", application->getName().c_str());
5585 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005586
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005587 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5588 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5589 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005590 postCommandLocked(std::move(commandEntry));
5591}
5592
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005593void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5594 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5595 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5596 commandEntry->obscuringPackage = obscuringPackage;
5597 postCommandLocked(std::move(commandEntry));
5598}
5599
chaviw3277faf2021-05-19 16:45:23 -05005600void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005601 const std::string& reason) {
5602 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5603 updateLastAnrStateLocked(windowLabel, reason);
5604}
5605
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005606void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5607 const std::string& reason) {
5608 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005609 updateLastAnrStateLocked(windowLabel, reason);
5610}
5611
5612void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5613 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005615 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 struct tm tm;
5617 localtime_r(&t, &tm);
5618 char timestr[64];
5619 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005620 mLastAnrState.clear();
5621 mLastAnrState += INDENT "ANR:\n";
5622 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005623 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5624 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005625 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626}
5627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005628void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 mLock.unlock();
5630
5631 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5632
5633 mLock.lock();
5634}
5635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005636void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 sp<Connection> connection = commandEntry->connection;
5638
5639 if (connection->status != Connection::STATUS_ZOMBIE) {
5640 mLock.unlock();
5641
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005642 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643
5644 mLock.lock();
5645 }
5646}
5647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005648void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005649 sp<IBinder> oldToken = commandEntry->oldToken;
5650 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005651 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005652 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005653 mLock.lock();
5654}
5655
arthurhungf452d0b2021-01-06 00:19:52 +08005656void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5657 sp<IBinder> newToken = commandEntry->newToken;
5658 mLock.unlock();
5659 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5660 mLock.lock();
5661}
5662
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005663void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005665
5666 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5667
5668 mLock.lock();
5669}
5670
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005671void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005672 mLock.unlock();
5673
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005674 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675
5676 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005677}
5678
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005679void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005680 mLock.unlock();
5681
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005682 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5683
5684 mLock.lock();
5685}
5686
5687void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5688 mLock.unlock();
5689
5690 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5691
5692 mLock.lock();
5693}
5694
5695void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5696 mLock.unlock();
5697
5698 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005699
5700 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005701}
5702
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005703void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5704 mLock.unlock();
5705
5706 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5707
5708 mLock.lock();
5709}
5710
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5712 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005713 KeyEntry& entry = *(commandEntry->keyEntry);
5714 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715
5716 mLock.unlock();
5717
Michael Wright2b3c3302018-03-02 17:19:13 +00005718 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005719 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005720 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005721 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5722 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005723 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725
5726 mLock.lock();
5727
5728 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005729 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005731 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005733 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5734 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736}
5737
chaviwfd6d3512019-03-25 13:23:49 -07005738void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5739 mLock.unlock();
5740 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5741 mLock.lock();
5742}
5743
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005744/**
5745 * Connection is responsive if it has no events in the waitQueue that are older than the
5746 * current time.
5747 */
5748static bool isConnectionResponsive(const Connection& connection) {
5749 const nsecs_t currentTime = now();
5750 for (const DispatchEntry* entry : connection.waitQueue) {
5751 if (entry->timeoutTime < currentTime) {
5752 return false;
5753 }
5754 }
5755 return true;
5756}
5757
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005758void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005760 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005762 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763
5764 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005765 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005766 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005767 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005769 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005770 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005771 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005772 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5773 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005774 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005775 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5776 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5777 connection->inputChannel->getConnectionToken(),
5778 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5779 finishTime);
5780 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005781
5782 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005783 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005784 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005785 restartEvent =
5786 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005787 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005788 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005789 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5790 handled);
5791 } else {
5792 restartEvent = false;
5793 }
5794
5795 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005796 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005797 // contents of the wait queue to have been drained, so we need to double-check
5798 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005799 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5800 if (dispatchEntryIt != connection->waitQueue.end()) {
5801 dispatchEntry = *dispatchEntryIt;
5802 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005803 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5804 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005805 if (!connection->responsive) {
5806 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005807 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005808 // The connection was unresponsive, and now it's responsive.
5809 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005810 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005811 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005812 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005813 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005814 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005815 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005816 } else {
5817 releaseDispatchEntry(dispatchEntry);
5818 }
5819 }
5820
5821 // Start the next dispatch cycle for this connection.
5822 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823}
5824
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005825void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5826 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5827 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5828 monitorUnresponsiveCommand->pid = pid;
5829 monitorUnresponsiveCommand->reason = std::move(reason);
5830 postCommandLocked(std::move(monitorUnresponsiveCommand));
5831}
5832
5833void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5834 std::string reason) {
5835 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5836 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5837 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5838 windowUnresponsiveCommand->reason = std::move(reason);
5839 postCommandLocked(std::move(windowUnresponsiveCommand));
5840}
5841
5842void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5843 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5844 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5845 monitorResponsiveCommand->pid = pid;
5846 postCommandLocked(std::move(monitorResponsiveCommand));
5847}
5848
5849void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5850 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5851 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5852 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5853 postCommandLocked(std::move(windowResponsiveCommand));
5854}
5855
5856/**
5857 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5858 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5859 * command entry to the command queue.
5860 */
5861void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5862 std::string reason) {
5863 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5864 if (connection.monitor) {
5865 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5866 reason.c_str());
5867 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5868 if (!pid.has_value()) {
5869 ALOGE("Could not find unresponsive monitor for connection %s",
5870 connection.inputChannel->getName().c_str());
5871 return;
5872 }
5873 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5874 return;
5875 }
5876 // If not a monitor, must be a window
5877 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5878 reason.c_str());
5879 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5880}
5881
5882/**
5883 * Tell the policy that a connection has become responsive so that it can stop ANR.
5884 */
5885void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5886 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5887 if (connection.monitor) {
5888 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5889 if (!pid.has_value()) {
5890 ALOGE("Could not find responsive monitor for connection %s",
5891 connection.inputChannel->getName().c_str());
5892 return;
5893 }
5894 sendMonitorResponsiveCommandLocked(pid.value());
5895 return;
5896 }
5897 // If not a monitor, must be a window
5898 sendWindowResponsiveCommandLocked(connectionToken);
5899}
5900
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005902 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005903 KeyEntry& keyEntry, bool handled) {
5904 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005905 if (!handled) {
5906 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005907 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005908 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005909 return false;
5910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 // Get the fallback key state.
5913 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005914 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005915 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005916 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917 connection->inputState.removeFallbackKey(originalKeyCode);
5918 }
5919
5920 if (handled || !dispatchEntry->hasForegroundTarget()) {
5921 // If the application handles the original key for which we previously
5922 // generated a fallback or if the window is not a foreground window,
5923 // then cancel the associated fallback key, if any.
5924 if (fallbackKeyCode != -1) {
5925 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005928 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005929 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005931 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005932 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933
5934 mLock.unlock();
5935
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005936 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938
5939 mLock.lock();
5940
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005941 // Cancel the fallback key.
5942 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944 "application handled the original non-fallback key "
5945 "or is no longer a foreground target, "
5946 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 options.keyCode = fallbackKeyCode;
5948 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950 connection->inputState.removeFallbackKey(originalKeyCode);
5951 }
5952 } else {
5953 // If the application did not handle a non-fallback key, first check
5954 // that we are in a good state to perform unhandled key event processing
5955 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005956 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005957 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005960 "since this is not an initial down. "
5961 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005962 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005964 return false;
5965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967 // Dispatch the unhandled key to the policy.
5968#if DEBUG_OUTBOUND_EVENT_DETAILS
5969 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005970 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005973 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005974
5975 mLock.unlock();
5976
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005977 bool fallback =
5978 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980
5981 mLock.lock();
5982
5983 if (connection->status != Connection::STATUS_NORMAL) {
5984 connection->inputState.removeFallbackKey(originalKeyCode);
5985 return false;
5986 }
5987
5988 // Latch the fallback keycode for this key on an initial down.
5989 // The fallback keycode cannot change at any other point in the lifecycle.
5990 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005991 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992 fallbackKeyCode = event.getKeyCode();
5993 } else {
5994 fallbackKeyCode = AKEYCODE_UNKNOWN;
5995 }
5996 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5997 }
5998
5999 ALOG_ASSERT(fallbackKeyCode != -1);
6000
6001 // Cancel the fallback key if the policy decides not to send it anymore.
6002 // We will continue to dispatch the key to the policy but we will no
6003 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006004 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6005 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006006#if DEBUG_OUTBOUND_EVENT_DETAILS
6007 if (fallback) {
6008 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 "as a fallback for %d, but on the DOWN it had requested "
6010 "to send %d instead. Fallback canceled.",
6011 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012 } else {
6013 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006014 "but on the DOWN it had requested to send %d. "
6015 "Fallback canceled.",
6016 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006017 }
6018#endif
6019
6020 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6021 "canceling fallback, policy no longer desires it");
6022 options.keyCode = fallbackKeyCode;
6023 synthesizeCancelationEventsForConnectionLocked(connection, options);
6024
6025 fallback = false;
6026 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006027 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006028 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006029 }
6030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031
6032#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033 {
6034 std::string msg;
6035 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6036 connection->inputState.getFallbackKeys();
6037 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006038 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006041 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 }
6043#endif
6044
6045 if (fallback) {
6046 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006047 keyEntry.eventTime = event.getEventTime();
6048 keyEntry.deviceId = event.getDeviceId();
6049 keyEntry.source = event.getSource();
6050 keyEntry.displayId = event.getDisplayId();
6051 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6052 keyEntry.keyCode = fallbackKeyCode;
6053 keyEntry.scanCode = event.getScanCode();
6054 keyEntry.metaState = event.getMetaState();
6055 keyEntry.repeatCount = event.getRepeatCount();
6056 keyEntry.downTime = event.getDownTime();
6057 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058
6059#if DEBUG_OUTBOUND_EVENT_DETAILS
6060 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006061 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006062 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063#endif
6064 return true; // restart the event
6065 } else {
6066#if DEBUG_OUTBOUND_EVENT_DETAILS
6067 ALOGD("Unhandled key event: No fallback key.");
6068#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006069
6070 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006071 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 }
6073 }
6074 return false;
6075}
6076
6077bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006078 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006079 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 return false;
6081}
6082
6083void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6084 mLock.unlock();
6085
Sean Stoutb4e0a592021-02-23 07:34:53 -08006086 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6087 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088
6089 mLock.lock();
6090}
6091
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092void InputDispatcher::traceInboundQueueLengthLocked() {
6093 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006094 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 }
6096}
6097
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006098void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 if (ATRACE_ENABLED()) {
6100 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006101 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6102 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 }
6104}
6105
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006106void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 if (ATRACE_ENABLED()) {
6108 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006109 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6110 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
6112}
6113
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006114void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006115 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006117 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 dumpDispatchStateLocked(dump);
6119
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006120 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006121 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006122 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 }
6124}
6125
6126void InputDispatcher::monitor() {
6127 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006128 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006130 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131}
6132
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006133/**
6134 * Wake up the dispatcher and wait until it processes all events and commands.
6135 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6136 * this method can be safely called from any thread, as long as you've ensured that
6137 * the work you are interested in completing has already been queued.
6138 */
6139bool InputDispatcher::waitForIdle() {
6140 /**
6141 * Timeout should represent the longest possible time that a device might spend processing
6142 * events and commands.
6143 */
6144 constexpr std::chrono::duration TIMEOUT = 100ms;
6145 std::unique_lock lock(mLock);
6146 mLooper->wake();
6147 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6148 return result == std::cv_status::no_timeout;
6149}
6150
Vishnu Naire798b472020-07-23 13:52:21 -07006151/**
6152 * Sets focus to the window identified by the token. This must be called
6153 * after updating any input window handles.
6154 *
6155 * Params:
6156 * request.token - input channel token used to identify the window that should gain focus.
6157 * request.focusedToken - the token that the caller expects currently to be focused. If the
6158 * specified token does not match the currently focused window, this request will be dropped.
6159 * If the specified focused token matches the currently focused window, the call will succeed.
6160 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6161 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6162 * when requesting the focus change. This determines which request gets
6163 * precedence if there is a focus change request from another source such as pointer down.
6164 */
Vishnu Nair958da932020-08-21 17:12:37 -07006165void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6166 { // acquire lock
6167 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006168 std::optional<FocusResolver::FocusChanges> changes =
6169 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6170 if (changes) {
6171 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006172 }
6173 } // release lock
6174 // Wake up poll loop since it may need to make new input dispatching choices.
6175 mLooper->wake();
6176}
6177
Vishnu Nairc519ff72021-01-21 08:23:08 -08006178void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6179 if (changes.oldFocus) {
6180 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006181 if (focusedInputChannel) {
6182 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6183 "focus left window");
6184 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006185 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006186 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006187 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006188 if (changes.newFocus) {
6189 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006190 }
6191
Prabir Pradhan99987712020-11-10 18:43:05 -08006192 // If a window has pointer capture, then it must have focus. We need to ensure that this
6193 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6194 // If the window loses focus before it loses pointer capture, then the window can be in a state
6195 // where it has pointer capture but not focus, violating the contract. Therefore we must
6196 // dispatch the pointer capture event before the focus event. Since focus events are added to
6197 // the front of the queue (above), we add the pointer capture event to the front of the queue
6198 // after the focus events are added. This ensures the pointer capture event ends up at the
6199 // front.
6200 disablePointerCaptureForcedLocked();
6201
Vishnu Nairc519ff72021-01-21 08:23:08 -08006202 if (mFocusedDisplayId == changes.displayId) {
6203 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006204 }
6205}
Vishnu Nair958da932020-08-21 17:12:37 -07006206
Prabir Pradhan99987712020-11-10 18:43:05 -08006207void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhanac483a62021-08-06 14:01:18 +00006208 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006209 return;
6210 }
6211
6212 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6213
Prabir Pradhanac483a62021-08-06 14:01:18 +00006214 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006215 setPointerCaptureLocked(false);
6216 }
6217
6218 if (!mWindowTokenWithPointerCapture) {
6219 // No need to send capture changes because no window has capture.
6220 return;
6221 }
6222
6223 if (mPendingEvent != nullptr) {
6224 // Move the pending event to the front of the queue. This will give the chance
6225 // for the pending event to be dropped if it is a captured event.
6226 mInboundQueue.push_front(mPendingEvent);
6227 mPendingEvent = nullptr;
6228 }
6229
6230 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhanac483a62021-08-06 14:01:18 +00006231 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006232 mInboundQueue.push_front(std::move(entry));
6233}
6234
Prabir Pradhan99987712020-11-10 18:43:05 -08006235void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00006236 mCurrentPointerCaptureRequest.enable = enabled;
6237 mCurrentPointerCaptureRequest.seq++;
Prabir Pradhan99987712020-11-10 18:43:05 -08006238 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6239 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
Prabir Pradhanac483a62021-08-06 14:01:18 +00006240 commandEntry->pointerCaptureRequest = mCurrentPointerCaptureRequest;
Prabir Pradhan99987712020-11-10 18:43:05 -08006241 postCommandLocked(std::move(commandEntry));
6242}
6243
6244void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6245 android::inputdispatcher::CommandEntry* commandEntry) {
6246 mLock.unlock();
6247
Prabir Pradhanac483a62021-08-06 14:01:18 +00006248 mPolicy->setPointerCapture(commandEntry->pointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006249
6250 mLock.lock();
6251}
6252
Vishnu Nair599f1412021-06-21 10:39:58 -07006253void InputDispatcher::displayRemoved(int32_t displayId) {
6254 { // acquire lock
6255 std::scoped_lock _l(mLock);
6256 // Set an empty list to remove all handles from the specific display.
6257 setInputWindowsLocked(/* window handles */ {}, displayId);
6258 setFocusedApplicationLocked(displayId, nullptr);
6259 // Call focus resolver to clean up stale requests. This must be called after input windows
6260 // have been removed for the removed display.
6261 mFocusResolver.displayRemoved(displayId);
6262 } // release lock
6263
6264 // Wake up poll loop since it may need to make new input dispatching choices.
6265 mLooper->wake();
6266}
6267
chaviw15fab6f2021-06-07 14:15:52 -05006268void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6269 // The listener sends the windows as a flattened array. Separate the windows by display for
6270 // more convenient parsing.
6271 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6272
6273 for (const auto& info : windowInfos) {
6274 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6275 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6276 }
6277 setInputWindows(handlesPerDisplay);
6278}
6279
Vishnu Nair41f77b82021-09-03 16:07:44 -07006280bool InputDispatcher::shouldDropInput(
6281 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6282 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6283 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6284 isWindowObscuredLocked(windowHandle))) {
6285 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6286 "%" PRId32 ".",
6287 NamedEnum::string(entry.type).c_str(), windowHandle->getName().c_str(),
6288 windowHandle->getInfo()->inputFeatures.string().c_str(),
6289 windowHandle->getInfo()->displayId);
6290 return true;
6291 }
6292 return false;
6293}
6294
Garfield Tane84e6f92019-08-29 17:28:41 -07006295} // namespace android::inputdispatcher